Write a C++ program to create a new string using first two characters of a given string. If the string length is less than 2 then return the original string

  • برمجة سي بلس بلس
  • برمجة

Write a C++ program to create a new string using first two characters of a given string. If the string length is less than 2 then return the original string

Sample Output:

He
Hi
H

الأجوبة

#include <iostream>
using namespace std;

string test(string s1)
         {
            return s1.length() < 2 ? s1 : s1.substr(0, 2);
         }
         
int main() 
 {
  cout << test("Hello") << endl;  
  cout << test("Hi") << endl;  
  cout << test("H") << endl;  
  cout << test(" ") << endl;    
  return 0;    
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...