0% found this document useful (0 votes)
13 views11 pages

Lecture 7-C++ Strings and String Manipulations

1) The document discusses C++ strings and various operations that can be performed on strings like defining, creating empty strings, finding the length, comparing strings, and extracting substrings. 2) Key string operations covered include using std::string to define strings, length() and size() to find string lengths, compare() to compare strings, and substr() to extract substrings given a starting position and optional length. 3) Examples are provided to demonstrate defining strings, finding lengths, comparing strings as equal, less than or greater than, and extracting substrings using substr() with different parameters.

Uploaded by

orodizodanielo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views11 pages

Lecture 7-C++ Strings and String Manipulations

1) The document discusses C++ strings and various operations that can be performed on strings like defining, creating empty strings, finding the length, comparing strings, and extracting substrings. 2) Key string operations covered include using std::string to define strings, length() and size() to find string lengths, compare() to compare strings, and substr() to extract substrings given a starting position and optional length. 3) Examples are provided to demonstrate defining strings, finding lengths, comparing strings as equal, less than or greater than, and extracting substrings using substr() with different parameters.

Uploaded by

orodizodanielo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lecture 7: C++ Strings

In C++, String is an object of class type std::string . This type of object represents a sequence or
string of characters, hence called a string.

Earlier, we mentioned printing out a string literal such as "Hello World" to standard output via:
std::cout << "Hello World.";

String constants consist of text enclosed in double quotes ("). The following is an example for a
string.
"Hello World"
This string contains 11 characters. In C++, the string constant is enclosed in double quotes.
string keyword is used to specify the datatype of a variable. Thus Strings are arrays of characters.
string s = "Hello World";

We can store these literals inside std::string type. C++ standard library offers a compound type
called string or rather std::string as it is part of the std namespace. We use it for storing and
manipulating strings.

In this tutorial, we will go through most used C++ String Operations with examples.

Basics about Strings


Defining a String
To use the std::string type, we need to include the <string> header in our program:
#include <iostream>
#include <string>
int main()
{
std::string s = "Hello World.";
}

To print out this string on the standard output we could also use (using namespace std;)
#include <iostream>
using namespace std;
int main()
{
string s = "Hello World.";
cout << s;
}

1|Page
@myco…TCBE 2202 Computing for Civil Engineering
Create Empty String
To create an empty string in C++, we can use double quotes. To create empty string using double
quotes, provide the quotes and give no character in the quotes. That returns an empty string.

In the following code snippet, we create an empty string using double quotes.

string name = "";


Example:
In the following program, we create empty strings using double quotes, and print the empty string
to console output.
main.cpp
#include <iostream>
using namespace std;

int main() {
string name = "";
cout << "Name : " << name;
}
Output
Name :

C++ String Length


String Length is the number of characters in a string. There are many ways in which you can find
the length of a string in C++. In this tutorial, we will go through some of the processes that use
built-in methods.

a) C++ String length using string.length()


length() is a member function of string class that returns the length of this string. In the following
example program, we shall take a string, and find its length using length() function.
C++ Program
#include <iostream>
using namespace std;

int main() {
string str = "Civil Engineering";
int len = str.length();
cout << "String Length : " << len << endl;
}
Output
String Length : 17
Program ended with exit code: 0

2|Page
@myco…TCBE 2202 Computing for Civil Engineering
b) C++ String length using string.size()
size() is a member function of string class that returns the number of characters in this string. In
the following example program, we shall take a string, and find its length using size() function.
C++ Program

#include <iostream>
using namespace std;

int main() {
string TCBE2202 = "Computing for Civil Engineering";
int len = TCBE2202.size();
cout << "String Length : " << len << endl;
}
Output

String Length : 31
Program ended with exit code: 0

c) C++ String length using strlen()


strlen() is a member function of cstring library. The function returns the number of characters
between the beginning of the string and the terminating null character of the char array passed as
argument.

In the following example program, we shall take a C style string, char array, and find its length
using strlen() function.

To use strlen() function, you have to include cstring header file at the start of your program.
C++ Program

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

int main() {
char str[] = "Civil Engineering";
int len = strlen(str);
cout << "String Length : " << len << endl;
}
Output

String Length : 17
Program ended with exit code: 0

3|Page
@myco…TCBE 2202 Computing for Civil Engineering
C++ String Comparison
String comparison means to check if the given two string are equal, if first string is greater than
second string, or if first string is less than second string.
std::string::compare() function in C++ compares two strings and returns a number. Based on the
return value, we can find the result of string comparison as given in the following table.
Consider the expression str1.compare(str2) , where we are comparing string str1 with
string str2 .

Return Value String Comparison Description


0 The two strings are equal.
Negative Value string str1 is less than the string str2.
Positive Value string str1 is greater than the string str2.

In this tutorial, we will go through an example, to demonstrate the string comparison using
compare() function.

Examples

a) Two Strings are Equal


In the following program, we take two strings: str1 and str2 such that both the string values
are same. We shall compare them using compare() function and observe the result.

C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "Michael";
string str2 = "Michael";
int result = str1.compare(str2);
cout << result << endl;
}
Output

0
Program ended with exit code: 0
compare() returned a value of 0.

4|Page
@myco…TCBE 2202 Computing for Civil Engineering
b) This String is Less than Other String
In the following program, we take two strings: str1 and str2 such that str1 is less
than str2 lexicographically. We shall compare them using compare() function and observe the
result.
C++ Program

#include <iostream>
using namespace std;
int main() {
string str1 = "apple";
string str2 = "cherry";
int result = str1.compare(str2);
cout << result << endl;
}
Output
-2
Program ended with exit code: 0
compare() returned a negative value.

c) This String is Greater than Other String


In the following program, we take two strings: str1 and str2 such that str1 is less
than str2 lexicographically (as written dictionaries). We shall compare them using compare()
function and observe the result.
C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "mango";
string str2 = "apple";
int result = str1.compare(str2);
cout << result << endl;
}
Output
12
Program ended with exit code: 0
compare() returned a positive value.

compare() return value: Please note that the value returned by compare() function is kind of a
difference of second string from first string.

5|Page
@myco…TCBE 2202 Computing for Civil Engineering
Find / Get / Access Strings
C++ Substring
To find the substring in a string, you can use substr() function, or use a looping technique to find
the substring yourself.

In this tutorial, we go through some of the processes to find a substring of a given string, given a
starting position, length or an ending position.

Syntax of substr() function


substr() is a member function of string class. Following is the syntax of substr() function.

substr (pos, len)


• substr() function is called on a string object.
• pos is the starting position or index of substring in this string.
• len is the number of characters in the substring.
• The default value of pos is zero. If pos is not specified, then the whole string is returned
as substring.
• len is optional. If len is not specified, the substring till the end of this string is returned.
• substr() returns a newly formed string object representing the substring formed using
this string, pos and len .

Example 1: substr() – Find Substring with start position and length


In this example, we take a string with some initial value and find the substring of this string starting
at given starting position and spanning a specified length.
C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "We are changing the world.";

int pos = 5;
int len = 10;
string substring = str1.substr(pos, len);

cout << substring;


}
Output
e changing
Note: Even if you provide a length that is out of the limit of the main string, len would be updated
such that substring ends at the end of the original string.

6|Page
@myco…TCBE 2202 Computing for Civil Engineering
Example 2: substr() – Find Substring with only start position
In this example, we take a string with some initial value and find the substring of this string starting
at given starting position. We do not provide the length of substring. The returned substring should
span from start position provided till the end of the string.

C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "We are changing the world.";

int pos = 5;
string substring = str1.substr(pos);

cout << substring;


}
Output
e changing the world.

Example 3: substr() – Find Substring with no start position


In this example, we take a string with some initial value and find the substring of this string. We
do not provide the start position of the substring. The returned string should be a copy of the
original string.

C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "We are changing the world.";

string substring = str1.substr();

cout << substring;


}
Output

We are changing the world.

7|Page
@myco…TCBE 2202 Computing for Civil Engineering
Example 4: substr() – Find Substring with start position and end position
In this example, we take a string with some initial value and find the substring of this string starting
at given starting position and ending at a given ending position. We know that substr() function
does not take end position, but length. So, we shall hack the len argument and form a length value
using start and end positions of substring in the original string.

C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "We are changing the world.";
int start = 5;
int end = 12;
string substring = str1.substr(start, end - start + 1);
cout << substring;
}
Output
e changi

Example 5: substr() – With start position out of range


If you provide a position to substr(), that is out of the range of the index in original string, you
will get std::out_of_range thrown in runtime.

C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "We are changing the world.";
int start = 50;
int len = 10;
string substring = str1.substr(start, len);
cout << substring;
}
Output

terminate called after throwing an instance of 'std::out_of_range'


what(): basic_string::substr: __pos (which is 50) > this-
>size() (which is 26)

8|Page
@myco…TCBE 2202 Computing for Civil Engineering
String Manipulations
The following tutorials cover use cases where part or whole of the string value is manipulated.

C++ String Append


C++ String Append – To append a string to another, you can use std::string::append() function
or use C++ Addition Operator + .

In this tutorial, we will learn the syntax and how to use these methods to append strings, with
example programs.

Syntax
The syntax of string.append() function to append string str2 to string str1 is

str1.append(str2);
string.append() function can be chained. Therefore, we can append() multiple strings to this string,
in a single statement.

str1.append(str2).append(str3);
Example 1: Append Single String
In the following program, we take two strings: str1 and str2 and append str2 to str1 using
string.append() function.
main.cpp

#include <iostream>
using namespace std;

int main() {
string str1 = "Hello";
string str2 = " World";
str1.append(str2);
cout << str1 << endl;
}

Output

Hello World
Program ended with exit code: 0

9|Page
@myco…TCBE 2202 Computing for Civil Engineering
Example 2: Append Multiple Strings
In the following program, we take three strings: str1 , str2 and str3 and
append str2 and str3 respectively to str1 using string.append() function in a single statement
using chaining mechanism.
main.cpp

#include <iostream>
using namespace std;

int main() {
string str1 = "Hello";
string str2 = " World.";
string str3 = " Welcome!";
str1.append(str2).append(str3);
cout << str1 << endl;
}
Output

Hello World. Welcome!


Program ended with exit code: 0

Concatenate Strings
To concatenate two or more strings in C++, use + operator.

In this tutorial, we will learn how to use + operator to concatenate two or more strings in C++,

with examples.

Syntax

The syntax to concatenate two strings str1 and str2 is

str1 + str2
The above expression returns the resulting string of the two strings concatenated in the given order.

We may concatenate more than two strings in a single statement.

str1 + str2 + str3


Examples:

10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 1: Concatenate Two Strings
In the following program, we take two strings: str1 and str2 and concatenate them using
addition operator.
C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "civil";
string str2 = " engineering";
string result = str1 + str2;
cout << result << endl;
}
Output

civil engineering
Program ended with exit code: 0

Example 2: Concatenate Multiple Strings


In the following program, we take three strings: str1 , str2 and str3 and concatenate them in
the same order and store the result in variable result .
C++ Program

#include <iostream>
using namespace std;

int main() {
string str1 = "skills";
string str2 = " in";
string str3 = " programming";
string result = str1 + str2 + str3;
cout << result << endl;
}

Output

skills in programming
Program ended with exit code: 0

11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy