String Functions in C++
There are several string functions present in Standard Template Library in C++ that are used to perform operations on strings. Some of the commonly used string functions are:
1. length() Function
Returns the length of a string.
Example
string str = "w3wiki";
cout << "The length of the string is: " << str.length();
2. substr() Function
It is used to extract a substring from a given string.
Syntax
string substr (size_t pos, size_t len) const;
pos: Position of the first character to be copied.
len: Length of the sub-string.
size_t: It is an unsigned integral type.
Example
C++
#include <iostream> #include <string> using namespace std; int main() { string str = "w3wiki" ; // Extracts a substring starting from // index 7 with a length of 5 string sub = str.substr(1, 5); cout << "Substring: " << sub << endl; return 0; } |
Substring: eeksf
3. append() Function
Appends a string at the end of the given string.
Example
C++
#include <iostream> #include <string> using namespace std; int main() { string str = "Geeksfor" ; str.append( "Geeks" ); cout << "Appended string: " << str << endl; return 0; } |
Appended string: w3wiki
4. compare() Function
It is used to compare two strings lexicographically.
Example
C++
#include <iostream> #include <string> using namespace std; int main() { string str1 = "Geeks" ; string str2 = "for" ; string str3 = "Geeks" ; int result1 = str1.compare(str2); cout << "Comparison result: " << result1 << endl; int result2 = str1.compare(str3); cout << "Comparison result: " << result2 << endl; return 0; } |
Comparison result: -31 Comparison result: 0
5. empty() Function
It is used to check if a string is empty.
Example
C++
#include <iostream> #include <string> using namespace std; int main() { string str1 = "w3wiki" ; string str2 = "" ; if (str1.empty()) { cout << "str1 is empty" << endl; } else { cout << "str1 is not empty" << endl; } if (str2.empty()) { cout << "str2 is empty" << endl; } else { cout << "str2 is not empty" << endl; } return 0; } |
str1 is not empty str2 is empty
C++ Cheatsheet
This is a C++ programming cheat sheet. It is useful for beginners and intermediates looking to learn or revise the concepts of C++ programming. While learning a new language, it feels annoying to switch pages and find different websites for different concepts that are easily understandable. You can learn C++ concepts very easily using this cheat sheet.
C++ is a high-level programming language. It was developed in 1983 by Bjarne Stroustrup at Bell Labs. It is used for developing various applications.
Contact Us