Manipulating Strings in C++
Introduction
A string is a sequence of character.We have used null terminated <char> arrays (C-strings or C-style strings) to store and manipulate strings.
ANSI C++ provides a class called string.
Commonly Used String Constructors
String();
// For creating an empty string.
String(const char *str);
// For creating a string object from a null-terminated string.
String(const string &str);
// For creating a string object from other string object
Creating String Objects
string s1, s3; // Using constructor with no arguments.
string s2(“xyz”); // Using one-argument constructor.
s1 = s2; // Assigning string objects
s3 = “abc” + s2; // Concatenating strings
cin >> s1; // Reading from keyboard (one word)
cout << s2; // Display the content of s2
getline(cin, s1) // Reading from keyboard a line of text
s3 += s1; // s3 = s3 + s1;
s3 += “abc”; // s3 = s3 + “abc”;
Manipulating String Objects
string s1(“12345”);
string s2(“abcde”);
s1.insert(4, s2); // s1 = 1234abcde5
s1.erase(4, 5); // s1 = 12345
s2.replace(1, 3, s1); // s2 = a12345e
Relational Operations
Operator Meaning
== Equality
!= Inequality
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
string s1(“ABC”); string s2(“XYZ”);
int x = s1.compare(s2);
x == 0 if s1 == s2
x > 0 if s1 > s2
x < 0 if s1 < s2
String Characteristics
void display(string &str)
{
cout << “Size = ” << str.size() << endl;
cout << “Length = ” << str.length() << endl;
cout << “Capacity = ” << str.capacity() << endl;
cout << “Max Size = ” << str.max_size() << endl;
cout << “Empty: ” << (str.empty() ? “yes” : “no”) << endl;
cout << endl << endl;
}
Accessing Characters in Strings
Function Task
size() Number of elements currently stored
length() Number of elements currently stored
capacity() Total elements that can be stored
max_size() Maximum size of a string object that a system can support
emply() Return true or 1 if the string is empty otherwise returns false or 0
resize() Used to resize a string object (effects only size and length)
Comments
Post a Comment