C++ Lec7-Strings
C++ Lec7-Strings
C++ Strings
Example
To use strings, you must include an additional header file in the source code, the <string> library:
Example
#include <iostream>
#include <string>
int main() {
return 0;
String Concatenation
The + operator can be used between strings to add them together to make a new string. This is
called concatenation:
Example
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
return 0;
}
In the example above, we added a space after firstName to create a space between John and
Doe on output.
However, you could also add a space with quotes (" " or ' '):
Example
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;
return 0;}
WARNING! C++ uses the + operator for both addition and concatenation. Numbers are added.
Strings are concatenated.
Example
#include <iostream>
using namespace std;
int main () {
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)
cout << z;
return 0;
}
Example
#include <iostream>
#include <string> If you try to add a number to a string, an
error occurs:
using namespace std;
int main () { Example
string x = "10"; string x = "10";
string y = "20"; int y = 20;
string z = x + y; // z will be 1020 (a string) string z = x + y;
cout << z;
return 0;
}
Programming C++ Samir Bilal Practical & Theoretical
4
String Length
Example
#include <iostream>
#include <string>
int main() {
cout << "The length of the txt string is: " << txt.length();
return 0;
Tip: You might see some C++ programs that use the size() function to get the length of a string.
This is just an alias of length(). It is completely up to you if you want to use length() or size():
Example
#include <iostream>
#include <string>
int main() {
cout << "The length of the txt string is: " << txt.size(); return 0;}
Access Strings
You can access the characters in a string by referring to its index number inside square brackets
[].
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
cout << myString[0]; // Outputs H
return 0;
}
Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
Example
#include <iostream>
#include <string>
int main() {
return 0;}
To change the value of a specific character in a string, refer to the index number, and use single
quotes:
Example
#include <iostream>
#include <string>
int main() {
myString[0] = 'F';
return 0;
Some Exercises:
1: Write a C++ program to output (print) the word (Erbil) then change the first
index of Erbil to (A) to print (Arbil) after that print just r and b letters from the
same word.
2: Write a C++ program to print the (Bismillahirrahmanirrahim) then find & print
the length (size) of its letters.