Actually C++ strings are two types
1. Traditional C style character string
2. String class type Introduces in Standard C++
Example of C-style string:
#include<iostream> using namespace std; int main() { char greetings[5]={'H','E','L','L','o'};//here one place is automatically adding by the compiler backslash zero \0 cout<<"Greetings: "; cout<<greetings<<endl; //we can define this manually to show actually it is working char greet[5]={'H','M','M','\0'}; cout<<"GREET: "; cout<<greet; return 0; }
Some builtin strings function came from language C
strcpy(s1,s2); //copies s2 into s1
strcat(s1,s2); //concatenates string s2 at the end of the string s1
strlen(s1); //returns the length of the string s1..length means actually size that means how many letters is in the string with white spaces and spaces
strcmp(s1,s2); //returns 0 if s1==s2 s1 and s2 are same if less than 0 s1<s2 and greater than 0 s1>s2
strchr(s1,ch);returns a pointer at the first occurence f character ch in string s1
strstr(s1,s2); //retruns a pointer to the first occurence of string s2 in string s1
Example here:
#include<iostream> #include<cstring> using namespace std; int main(){ char str1[10]={"Hello"}; char str2[10]={"Zaki"}; char str3[10]; int doirgho; strcpy(str3,str1);//copy str1 into str3 cout<<"strcpy: "<<str3<<endl; strcat(str1,str2); cout<<"strcat: "<<str1<<endl; doirgho=strlen(str1); cout<<"Length: "<<doirgho<<endl; return 0; }
In C++ Standard String Class:
Here we are using the library header #include<string> that is c++ built in header for strings manipulation…
#include<iostream> #include<string> using namespace std; int main() { string str1="Hello"; string str2="World"; string str3; int doirgho; str3=str1;//copy str1 into str3 cout<<"str3: "<<str3<<endl; //concatening str1 and str2 str3=str1+str2; cout<<"str1+str2: "<<str3<<endl; //total length of str3 after concatenation doirgho=str3.size(); cout<<"str3.size(): "<<doirgho<<endl; return 0; }