A string is a sequence of characters.
In C++, strings can be represented in two ways:
C-style strings (character arrays)
String class (from
<string>library)
Strings are used to store words, sentences, or any textual data.
C-Style Strings
These are arrays of characters ending with a null character
\0.Null character
\0indicates the end of the string.
Declaration Syntax:
Initialization Examples:
Important Notes:
Maximum length = size of array – 1 (because of
\0)Cannot directly assign new strings using
=after declaration.
Input and Output
Printing C-style Strings:
Input C-style Strings:
Limitation:
cinreads input only until space.To read full sentence, use
cin.getline():
C-Style String Functions
C++ provides string handling functions in <cstring> library.
strlen()– Length of string
strcpy()– Copy string
strcat()– Concatenate strings
strcmp()– Compare strings
strchr()– Find character in string
strstr()– Find substring
Limitations of C-Style Strings
Fixed size; cannot grow dynamically
Manual null character required
Harder to manipulate
Functions are from C library, not fully type-safe
String Class in C++
C++ provides string class in <string> library.
Declaration:
Advantages over C-style strings:
Dynamic size; grows automatically
Supports operators like
+for concatenationEasier functions to manipulate strings
No need for null character
\0
String Input and Output
Using cin and cout:
Using getline() for full sentence:
String Functions and Operators
Concatenation:
Length of String:
Access Character:
Substring:
Find:
Replace:
Erase:
Compare:
Examples Using String Class
Concatenate two strings
Find the length of string
Input full name using
getline()Convert string to uppercase (using loop)
Count vowels in string
Reverse a string
Check palindrome string
Replace a word in a sentence
Find substring index
Compare two strings
Example 1: Count Vowels
Example 2: Reverse String
Example 3: Check Palindrome
Example 4: Replace Word
Example 5: Substring
Example 6: Find Word Position
Example 7: Concatenate Strings
Example 8: Compare Strings
Example 9: Erase Part of String
Example 10: Convert to Uppercase
Extra Details
C-style strings are low-level, faster, but harder to use
String class is easier, safer, and dynamic
Use string class in modern C++ unless performance is critical
Can combine string class and C-style strings if needed
Strings can be passed to functions, returned from functions