String Handling

String handling in C++ refers to working with text data such as words and sentences. C++ provides powerful ways to create, modify, compare, and manipulate strings easily.

What is a String?

A string is a sequence of characters used to store text.

Examples:

"Hello"
"Programming"
"C++ Language"

Why String Handling is Important

String handling is important because it:

  • Helps process text data
  • Is used in user input and output
  • Supports searching and editing text
  • Is widely used in real-world applications

String Library in C++

C++ provides the <string> library for easier string handling.

#include <string>

Declaring a String

string name;

Initializing a String

string name = "Ali";

Example Program

#include <iostream>
#include <string>
using namespace std;

int main() {

string name = "Ahmed";

cout << name;

return 0;
}

Taking String Input

Single Word Input

cin >> name;

Full Sentence Input

getline(cin, name);

Example of getline()

#include <iostream>
#include <string>
using namespace std;

int main() {

string sentence;

getline(cin, sentence);

cout << sentence;

return 0;
}

Common String Functions

length()

Used to find string length.

string text = "Programming";

cout << text.length();

append()

Used to join strings.

string a = "Hello ";
string b = "World";

a.append(b);

cout << a;

+ Operator

Strings can also be combined using +.

string full = "C++ " + string("Programming");

substr()

Used to extract part of a string.

string text = "Programming";

cout << text.substr(0, 6);

find()

Used to search text inside a string.

string text = "Hello World";

cout << text.find("World");

Comparing Strings

string a = "Ali";
string b = "Ahmed";

if (a == b) {
cout << "Same";
} else {
cout << "Different";
}

Loop Through String Characters

#include <iostream>
#include <string>
using namespace std;

int main() {

string text = "Hello";

for (int i = 0; i < text.length(); i++) {
cout << text[i] << endl;
}

return 0;
}

Advantages of String Class

  • Easy to use
  • Dynamic size
  • Built-in functions available
  • Safer than character arrays

Difference Between String and Character Array

String ClassCharacter Array
Dynamic sizeFixed size
Easier handlingManual handling
Built-in functionsLimited functions
SaferLess safe

Why String Handling is Important

String handling is important because it:

  • Helps process user data
  • Is used in text-based applications
  • Supports file and web development
  • Simplifies programming tasks

Real-Life Example

Think of a text editor:

  • You write text
  • Edit words
  • Search sentences
  • Combine paragraphs

All these operations use string handling.

Conclusion

String handling in C++ allows programmers to efficiently work with text data using powerful built-in functions and the string class. It is an essential concept for creating interactive and real-world applications.

Home » Intermediate C++ > Arrays and Strings > String Handling