Chapter 3 Strings in c++ programming
Chapter 3 Strings in c++ programming
C++ Strings
• Syntax :
• Examples :
• char city[30];
• char name[20];
• char message[50];
#include <iostream>
#include <string>
using namespace std;
void main ()
{string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
str3 = str1; // copy str1 into str3
cout << "str3 : " << str3 << endl;
// concatenates str1 and str2
str3 = str1 + str2;
cout << "str3 : " << str3 << endl;
len = str3.size();
cout << "str3.size() : " << len <<endl; 12
Compiled By Dagne Walle
}
Strings in C++ Programs
Output :
g r e e n \0
#include <iostream>
#include <cstring>
using namespace std;
void main() {
char str1[] =“Dagne";
char *str2 = “Girmaw";
strcpy(str1,str2);
cout<<str1<<endl;
}
Compiled By Dagne Walle 24
String Copy (strncpy)
strncpy(s1, s2) → s1[n] = s2[n]
#include <iostream>
#include <cstring>
using namespace std;
void main() {
char str1[] = ”Dagne";
char *str2 = “Walle Girmaw";
strncpy(str1,str2,5);
cout<<str1<<endl;
}
Compiled By Dagne Walle 25
String Concat (strcat)
• strncat( ) function in C language concatenates (appends) portion
of one string at the end of another string.
• Syntax : strncat ( destination_string , source_string, size);
• Example:-strncat ( str2, str1, 3 ); – First 3 characters of str1 is
concatenated at the end of str2.
• As you know, each string in C is ended up with null character
(‘\0’).
• In strncat( ) operation, null character of destination string is
overwritten by source string’s first character and null character is
added at the end of new destination string which is created after
strncat( ) operation.
You can also concatenate C++ strings using the + and += operators:
string s = “ABCD*FG”;
string s2 = “Robot”;
string s5 = “Soccer”;
string s6 = s + “HIJK”; //changes s6 to “ABCD*FGHIJK
void main() {
char str1[24] = ”Haramaya";
char *str2 = “University";
strcat(str1,str2);
cout<<str1<<endl;
}
#include <iostream>
#include <cstring>
using namespace std;
void main() {
char str1[24] = ”Haramaya";
char *str2 = “University of Ethiopia";
strncat(str1,str2,10);
cout<<str1<<endl;
}
• Syntax : strlen(str);
The C++ string class also defines a length() function for extracting
how many characters are stored in a string.
string s = “ABCDEFG”;
const char* cs = s.c_str();
s6 = “ABCD*FGHIJK”;
s4 = s6.substr(5, 3); //changes s4 to “FGH”
s6 = “ABCD*FGHIJK”;
s6.erase(4, 2); //changes s6 to “ABCDGHIJK”;
find() function
returns the index of the first occurrence of a given substring:
Swapping strings
• s1.swap(s2);
– Switch contents of two strings
• Find functions
– s1.find_last_of( s2 )
• Finds last occurrence of any character in s2
– s1.find_first_not_of( s2 )
• Finds first character NOT in s2
– s1.find_last_not_of( s2 )
• Finds last character NOT in s2
• s1.insert( index, s2 )
– Inserts s2 before position index
• s1.insert( index, s2, index2, N );
– Inserts substring of s2 before position index
– Substring is N characters, starting at index2