The following table lists some operations programs often need to perform. The table details how C++ supports these operations for C-strings and string objects. The following references provide a complete list and greater detail.
string Class | C-String |
---|
Creation & Initialization | |
string s1("hello"); string s2("world");
|
char* s1 = "hello"; (content of s1 is constant)char s2[50] = "world"; (content of s2 can change) |
Creation Empty | |
string s3; |
char s3[100] = ""; char s3[100]; + s3[0] = '\0'; |
Input / Read | |
string s4; getline(cin, s4); |
char s4[50]; cin.getline(s4, 50);
|
Test For Equality | |
s1 == s2 |
strcmp(s1,s2) == 0 !strcmp(s1,s2)
|
Test For Inequality | |
s1 != s2 |
strcmp(s1,s2) != 0 strcmp(s1,s2)
|
Ordering | |
s1 < s2 (does s1 come before s2)
|
strcmp(s1,s2) < 0
|
s1 <= s2
|
strcmp(s1,s2) <= 0
|
s1 > s2 (does s1 come after s2)
|
strcmp(s1,s2) > 0
|
s1 >= s2
|
strcmp(s1,s2) >= 0
|
s1.compare(s2)
|
strcmp(s1,s2)
|
Character Access | |
s1[i] no bounds checkings1.at(i) bounds checking enabled
|
s1[i] no bounds checking
|
st.front() |
s1[0] |
s1.back() |
s1[strlen(s1) - 1] |
Length Operations | |
s1.length() s1.size()
|
strlen(s1)
|
s1.empty() |
strlen(s1) == 0 |
Clearing (Complete Data Removal) | |
s1.clear() s1.erase()
|
s1[0] = '\0'
|
Shortening (Partial Data Removal) | |
s1.erase(start)
|
s1[start] = '\0'
|
Copying | |
s3 = s1 |
strcpy(s3, s1) |
Concatenation | |
s3 += s2
|
strcat(s3, s2)
|
s3 = s1 + s2 |
|
Searching | |
s1.find("llo") 1 (find substring, left to right)
|
strstr(s1, "llo")
|
s1.rfind("llo") 1 (find substring, reverse or right to left)
|
|
s1.find('h') 2 (find character, left to right)
|
strchr(s1, 'h')
|
s1.rfind('h') 2 (find character, reverse or right to left) |
strrchr(s1, 'h') |
s1.find_first_of("llo") 1, 3 (find character, left to right) |
strpbrk(s1, "llo") |
s1.find_last_of("llo") 1, 3 (find character, reverse or right to left) |
|
s1.find_first_of('h') 2 |
strchr(s1, 'h') |
s1.find_last_of('h') 2 |
strrchr(s1, 'h') |
string ↔ C-string | |
Convert string to C-strings1.c_str(); s1.data(); |
Convert C-string to stringstring s4("Hello"); string s5(s1); |