0% found this document useful (0 votes)
41 views75 pages

Strings

The document discusses different types of strings in C/C++. It describes string literals, C-style strings stored in character arrays, and C++ std::string class. It provides examples of declaring and manipulating each string type, including accessing characters, modifying strings, and ensuring strings are null-terminated. Key differences between each type are highlighted, such as C-style strings requiring manual memory management while std::string handles this automatically.

Uploaded by

Swastik Sharma
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)
41 views75 pages

Strings

The document discusses different types of strings in C/C++. It describes string literals, C-style strings stored in character arrays, and C++ std::string class. It provides examples of declaring and manipulating each string type, including accessing characters, modifying strings, and ensuring strings are null-terminated. Key differences between each type are highlighted, such as C-style strings requiring manual memory management while std::string handles this automatically.

Uploaded by

Swastik Sharma
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/ 75

C Strings

Types of Strings
1. String Literals:
“Hello World”
“xyz 123 *&^#$!”

2. C-style strings:
char s[20];

3. C++ class string;


string s;

2
literalString.cpp
...
int main()
{
char s[] = "Hello World";

cout << s << endl;

for (int i = 0; i < 11; i++)


{ cout << s[i] << ","; }

cout << endl;


...

3
literalString.cpp
...
char s[] = "Hello World";

cout << s << endl;

for (int i = 0; i < 11; i++)


{ cout << s[i] << ","; }

cout << endl;


...

> literalString.exe
Hello World
H,e,l,l,o, ,W,o,r,l,d,

4
Literal String
• To create a variable containing a literal string:
char s[] = “Hello World”;

• char s[] means an array of characters;

• This variable cannot be changed, i.e., the following will


generate a syntax error:

char s[] = “Hello World”;


s = “Goodbye World”; // Syntax Error

5
ascii.cpp
...
int main()
{
char s[] = "Hello World";

cout << s << endl;

for (int i = 0; i < 11; i++)


{ cout << setw(4) << s[i] << ","; }
cout << endl;

for (int i = 0; i < 11; i++)


{ cout << setw(4) << int(s[i]) << ","; }
cout << endl;

return 0;
}

6
...
char s[] = "Hello World";

cout << s << endl;

for (int i = 0; i < 11; i++)


{ cout << setw(4) << s[i] << ","; }
cout << endl;

for (int i = 0; i < 11; i++)


{ cout << setw(4) << int(s[i]) << ","; }
cout << endl;
...

> ascii.exe
Hello World
H, e, l, l, o, , W, o, r, l, d,
72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100,
>

7
null Character
• Literal strings end in a null character: ‘\0’.
(Character ‘\0’ has ASCII code 0.)
char s[] = “Hello World”;

– s[0] equals ‘H’;


– s[1] equals ‘e’;
...
– s[8] equals ‘r’;
– s[9] equals ‘l’;
– s[10] equals ‘d’;
– s[11] equals ‘\0’;

8
literalString2.cpp
...
int i;
char s[] = "Hello World";

cout << s << endl;

i = 0;
while(s[i] != '\0')
{
cout << s[i] << ",";
i++;
}
cout << endl;

cout << "s[" << i << "] = " << int(s[i]) << endl;
...

9
literalString2.cpp
cout << s << endl;

i = 0;
while(s[i] != '\0')
{
cout << s[i] << ",";
i++;
}
cout << endl;

cout << "s[" << i << "] = " << int(s[i]) << endl;

> literalString2.exe
Hello World
H,e,l,l,o, ,W,o,r,l,d,
s[11] = 0

10
ascii2.cpp
...
i = 0;
while(s[i] != '\0')
{
cout << setw(4) << s[i] << ",";
i++;
}
cout << endl;

i = 0;
while(s[i] != '\0')
{
cout << setw(4) << int(s[i]) << ",";
i++;
}
cout << setw(4) << int(s[i]);
cout << endl;
...
11
...
i = 0;
while(s[i] != '\0')
{
cout << setw(4) << int(s[i]) << ",";
i++;
}
cout << setw(4) << int(s[i]);
cout << endl;
...

> ascii2.exe
Hello World
H, e, l, l, o, , W, o, r, l, d,
72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 0
>

12
C-style strings
• A C-style string is stored in an array of char;
• C-style strings should always end in ‘\0’;

const int MAX_LENGTH(20);


char s[MAX_LENGTH] =
{ 'H', 'e', 'l', 'l', 'o', ' ',
'W', 'o', 'r', 'l', 'd', '\0'};

cout << "String = " << s << endl;

13
cString.cpp
const int MAX_LENGTH(20);
// C-style strings should always end in '\0'
char s[MAX_LENGTH] =
{ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};

cout << "String = " << s << endl;

s[1] = 'o';
s[2] = 'w';
s[3] = 'd';
s[4] = 'y';
cout << "String = " << s << endl;

s[5] = '\0';
cout << "String = " << s << endl;

14
cString.cpp
const int MAX_LENGTH(20);
// C-style strings should always end in '\0'
char s[MAX_LENGTH] =
{ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};
cout << "String = " << s << endl;
s[1] = 'o';
s[2] = 'w';
s[3] = 'd';
s[4] = 'y';
cout << "String = " << s << endl;
s[5] = '\0';
cout << "String = " << s << endl;

> cString.exe
String = Hello World
String = Howdy World
String = Howdy

15
Literal String
• A literal string variable cannot be changed, i.e., the
following will generate a syntax error:

char s[] = “Hello World”;


s = “Goodbye World”; // Syntax Error

• However, individual characters within the string can be


changed:
s[1] = 'o';
s[2] = 'w';

• A literal string should ALWAYS contain ‘\0’.

16
Capitalize
Change all characters in a string to capitals.

Input: Hello World


Output: HELLO WORLD

17
ASCII Code
Code Char Code Char Code Char Code Char
32 Space 48 0 65 A 97 a
33 ! 49 1 66 B 98 b
34 " 50 2 67 C 99 c
35 # 51 3 68 D 100 d
36 $ 52 4 69 E 101 e
37 % 53 5 70 F 102 f
38 & 54 6 71 G 103 g
39 ' 55 7 72 H 104 h
40 ( 56 8 73 I 105 i
41 ) 57 9 74 J 106 j
… … … … … … … …

18
capitalize.cpp
...
char s[] = "Hello World";
int ascii_code(0);
int i(0);

cout << s << endl;

i = 0;
while(s[i] != '\0')
{
ascii_code = int(s[i]);
if (97 <= ascii_code && ascii_code <= 122)
{ ascii_code = ascii_code-32; }
cout << char(ascii_code);
i++;
}
cout << endl;
...
19

i = 0;
while(s[i] != '\0')
{
ascii_code = int(s[i]);
if (97 <= ascii_code && ascii_code <= 122)
{ ascii_code = ascii_code-32; }
cout << char(ascii_code);
i++;
}

> capitalize.exe
Hello World
HELLO WORLD

20
passLiteral.cpp
...
int main()
{
int x1, y1;
int x2, y2;

read_point("Enter first point: ", x1, y1);


read_point("Enter second point: ", x2, y2);

write_point("First point: ", x1, y1);


write_point("Second point: ", x2, y2);

return 0;
}
...

21
passLiteral.cpp
...
void read_point(const char prompt[], int & x, int & y);
void write_point(const char label[], int x, int y);

int main()
{
int x1, y1;
int x2, y2;

read_point("Enter first point: ", x1, y1);


read_point("Enter second point: ", x2, y2);

write_point("First point: ", x1, y1);


write_point("Second point: ", x2, y2);

return 0;
}
...
22
Functions read_point() and write_point()

void read_point(const char prompt[], int & x, int & y)


{
cout << prompt;
cin >> x;
cin >> y;
}

void write_point(const char label[], int x, int y)


{
cout << label;
cout << "(" << x << "," << y << ")" << endl;
}

23

read_point("Enter first point: ", x1, y1);
read_point("Enter second point: ", x2, y2);

void read_point(const char prompt[], int & x, int & y)


{
cout << prompt;
cin >> x;
cin >> y;
}

> passLiteral.exe
Enter first point: 10 20
Enter second point: 3 5
First point: (10,20)
Second point: (3,5)

24

write_point("First point: ", x1, y1);
write_point("Second point: ", x2, y2);

void write_point(const char label[], int x, int y)


{
cout << label;
cout << "(" << x << "," << y << ")" << endl;
}

> passLiteral.exe
Enter first point: 10 20
Enter second point: 3 5
First point: (10,20)
Second point: (3,5)

25
(Major) Problems with C-style Strings
const int MAX_LENGTH(20);
char s[MAX_LENGTH] = { 'H', 'e', 'l', 'l', 'o', '\0'};
cout << "String = " << s << endl;

• Forgetting to end the string with ‘\0’;


• Not allocating enough memory for the string;

• How do you add an element to a string?


• How do you delete an element from a string?
• How do you concatenate two strings?

26
C++ Strings
C++ class string
• C++ class string requires:
#include <string>
using namespace std;

• To create a variable of type string, simply:


string lastName;

• Assignment, as always is the same:


lastName = “Marx”;

• Or combine the two with an initialization:


string lastName(“Marx”);

Or
string lastname = “Marx”;

28
String Operators: Assignment
• Assignment (=): As with before, assign a
string to a variable of type string.

string lastName(“Marx”), anothername;

anothername = lastName;

• Both now hold “Marx”

29
String Operators: Concatentation

• Concatenation (+): Puts a string


on the end of another.

string firstName(“Groucho”);
string lastName(“Marx”);
string fullname = firstName + lastname;

30
concatString.cpp
#include <iostream>
#include <string> // <--------- Note
using namespace std;

int main()
{
string name1("Groucho“), name2(“Harpo”);
string lastName("Marx“);

string fullName1 = name1 + lastName;


string fullName2 = name2 + lastName;

cout << fullName1 << endl;


cout << fullName2 << endl;

31
concatString.cpp
#include <iostream>
#include <string> // <--------- Note
...
{
string name1("Groucho“), name2(“Harpo”);
string lastName("Marx“);

string fullName1 = name1 + lastName;


string fullName2 = name2 + lastName;

cout << fullName1 << endl;


cout << fullName2 << endl;

> concatString.exe
GrouchoMarx
HarpoMarx

32
concatString2.cpp
#include <iostream>
#include <string> // <--------- Note
using namespace std;

int main()
{
string name1("Groucho“), name2(“Harpo”);
string lastName("Marx“);

// separate first and last names with a blank


string fullName1 = name1 + " " + lastName;
string fullName2 = name2 + " " + lastName;

cout << fullName1 << endl;


cout << fullName2 << endl;

33
concatString2.cpp
#include <iostream>
#include <string> // <--------- Note
...
{
string name1("Groucho“), name2(“Harpo”);
string lastName("Marx“);

// separate first and last names with a blank


string fullName1 = name1 + " " + lastName;
string fullName2 = name2 + " " + lastName;

cout << fullName1 << endl;


cout << fullName2 << endl;

> concatString.exe
Groucho Marx
Harpo Marx

34
C++ String I/O
Input/Output with Strings
• I/O with Strings are as before:

string lastName;

cout << “Please enter your last name: “;


cin >> lastName; // get the last name

cout << “Your last name is “ << lastName;

36
getName.cpp
#include <iostream>
#include <string>
using namespace std;

int main()
{
string firstName, lastName, fullName;

cout << "Enter your first name: ";


cin >> firstName;

cout << "Enter your last name: ";


cin >> lastName;

// concatenate
fullName = firstName + " " + lastName;
cout << "Your name is: " << fullName << endl;

37
getName.cpp
string firstName, lastName, fullName;

cout << "Enter your first name: ";


cin >> firstName;

cout << "Enter your last name: ";


cin >> lastName;

// concatenate
fullName = firstName + " " + lastName;
cout << "Your name is: " << fullName << endl;

> getName.exe
Enter your first name: Groucho
Enter your last name: Marx
Your name is: Groucho Marx

38
getName2.cpp
#include <iostream>
#include <string>
using namespace std;

int main()
{
string fullName;

cout << "Enter your full name: ";


cin >> fullName;
cout << "Your name is: " << fullName << endl;

return 0;
}

39
getName2.cpp
...
string fullName;

cout << "Enter your full name: ";


cin >> fullName;
cout << "Your name is: " << fullName << endl;
...

> getName2.exe
Enter your full name: Groucho Marx
Your name is: Groucho

40
Input/Output with Strings
• A common problem with reading strings from
user input is that it could contain white spaces.
• cin uses white space (e.g. space, tab, newline)
as a delimiter between inputs;

cin >> fullName;

> getName2.exe
Enter your full name: Groucho Marx
Your name is: Groucho

41
String I/O: getline()
• Fortunately, the string class let’s us get
around this with the getline() function.

• Syntax: getline(source, destination)


• source is the source of the string. In our
case, we want cin here.
• destination is the string variable where
we want the string to be read into.

42
String I/O: getline()
• We can fix our code by rewriting it as
follows:

string fullname;

cout << “Enter your full name: ”;


getline(cin, fullname);

43
getName3.cpp
#include <iostream>
#include <string>
using namespace std;

int main()
{
string fullName;

cout << "Enter your full name: ";


getline(cin, fullName); // <--------- Note
cout << "Your name is: " << fullName << endl;

return 0;
}

44
getName3.cpp
...
cout << "Enter your full name: ";
getline(cin, fullName); // <--------- Note
cout << "Your name is: " << fullName << endl;
...

> getName3.exe
Enter your full name: Groucho Marx
Your name is: Groucho Marx

> getName3.exe
Enter your full name: Groucho G. Marx III
Your name is: Groucho G. Marx III

45
getName3.cpp
...
cout << "Enter your full name: ";
getline(cin, fullName); // <--------- Note
cout << "Your name is: " << fullName << endl;
...

> getName3.exe
Enter your full name: Groucho Marx
Your name is: Groucho Marx

> getName3.exe
Enter your full name:
Your name is:

46
C++ String Processing
str[k]
• s[k] represents the k’th character in string s:

string s(“Hello World”);

// the character ‘H’ will be output.


cout << s[0] << endl;

// the character ‘W’ will be output.


cout << s[6] << endl;

48
String Processing (2)
• s[k] represents the (k+1)’st character in string s:

string s(“Hello World”);

s[1] = ‘o’;
s[2] = ‘w’;
s[3] = ‘d’;
s[4] = ‘y’;

// output “Howdy World”


cout << s << endl;

49
Relational String Operators
== !=
< <=
> >=

• == and != are same as before, but the others


are not exactly like usage with numbers…

• For instance, what exactly does it mean if one


string is “less than” another?

50
...
relationOps.cpp
string s1, s2;
cout << "Enter first string: ";
getline(cin, s1);

cout << "Enter second string: ";


getline(cin, s2);

if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}

51
relationOps.cpp
if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}

> relationOps.exe
Enter first string: hello
Enter last string: howdy
hello < howdy

52
relationOps.cpp
if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}

> relationOps.exe
Enter first string: hello
Enter last string: Howdy
hello > Howdy

53
relationOps.cpp
if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}

> relationOps.exe
Enter first string: Hello
Enter last string: Hello World

(What will be the output?)

54
relationOps.cpp
• Blanks matter:

> relationOps.exe
Enter first string: HelloWorld
Enter last string: Hello World
HelloWorld > Hello World

55
sortNames.cpp
...
int main()
{
const int MAX_SIZE(50);
string name[MAX_SIZE];
int num_names(0), i(0);
string s;

// Read names
i = 0;
cout << "Enter name: ";
cin >> s;
while (s != ".“ && i < MAX_SIZE)
{
name[i] = s;
i++;
cout << "Enter name: ";
cin >> s;
}
num_names = i;
...

56
sortNames.cpp (2)
...
// Sort names
for (int i = num_names-1; i > 0; i--)
{
// Compare name[j] with name[i], j < i
for (int j = 0; j < i; j++)
{
if (name[j] > name[i])
{
swap(name[j], name[i]);
}
}
// name[i] is now in its correct location
}
...

57
sortNames.cpp (3)
...
// Output names
cout << endl;
cout << "Names in alphabetic order:" << endl;
for (int i = 0; i < num_names; i++)
{
cout << name[i] << endl;
}

return 0;
}

58
String Processing
• In addition to giving us a new data type to
hold strings, the string library offers many
useful string processing methods.

• You can find most of them of them in the


book, but here are a few useful ones.

59
length()
• This method returns the integer length of the
string. (Note: Parentheses “()” after length().)

• Example:
string s1(“Super!”);

//the integer 6 will be output.


cout << s1.length() << endl;

60
easyFrench.cpp
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);

for (int i = 0; i < s.length(); i++)


{
if (s[i] == 's') {
s[i] = 'z';
}
else if (s[i] == 'w') {
s[i] = 'v';
}
}

cout << "French version: ";


cout << s << endl;
...
61
substr(index, n)
• Returns the string consisting of n characters
starting from the specified index.

• Example:

string transport(“Cruise Ship”);

//outputs “Ship”
cout << transport.substr(7, 4) << endl;

62
replace(index, n, str)
• Removes n characters in the string starting from
the specified index, and inserts the specified
string, str, in its place.

• Example:

string transport(“Speed Boat”);

transport.replace(0, 5, “Sail”);

// outputs “Sail Boat”


cout << transport << endl;

63
advancedFrench.cpp
// example of using C++ class string

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

int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);

64
advancedFrench.cpp
...
for (int i = 0; i < s.length(); i++)
{
if (s[i] == 's')
{
s[i] = 'z';
}
else if (s[i] == 'w')
{
s[i] = 'v';
}
else if (s.substr(i, 5) == " the ")
{
s.replace(i, 5, " la ");
}
}

cout << "French version: ";


cout << s << endl;
return 0;
}

65
insert(index, str)
• Inserts the specified string at the specified index.

• Example:

string animal(“Hippo”);

animal.insert(0, “Happy ”);

//outputs “Happy Hippo”


cout << animal << endl;

66
outputFileName.cpp
// construct an output file name from the input file name

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

int main()
{
string input_filename, output_filename;
int length(0);

cout << "Enter input file name: ";


cin >> input_filename;
...

67
outputFileName.cpp
...
length = input_filename.length();
output_filename = input_filename;
if (input_filename.substr(0,2) == "in")
{
output_filename.replace(0,2,"out");
}
else
{
output_filename.insert(0, "out.");
}

cout << "Output file name: " << output_filename << endl;

return 0;
}

68
CanadianError.cpp
...
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '.' || s[i] == '?')
{
s.replace(i, 1, ", eh?");
}
}
cout << "Canadian version: ";
cout << s << endl;
return 0;
}

69
Canadian.cpp
...
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '.' || s[i] == '?')
{
s.replace(i, 1, ", eh?");
i = i + 4; // Why 4?
}
}
cout << "Canadian version: ";
cout << s << endl;
return 0;
}

70
Literal vs. C++ strings
• Literal strings end in a null character: ‘\0’.
(Character ‘\0’ has ASCII code 0.)
char s[] = “Hello World”;
– s[11] equals ‘\0’;

• C++ strings DO NOT end in a null character: ‘\0’.


string s2(“Hello World”);
– s2[11] DOES NOT exist!

71
Passing Strings to Functions
outputFileName.cpp
...
length = input_filename.length();
output_filename = input_filename;
if (input_filename.substr(0,2) == "in")
{
output_filename.replace(0,2,"out");
}
else
{
output_filename.insert(0, "out.");
}

cout << "Output file name: " << output_filename << endl;
...

73
Function construct_output_filename()
void construct_output_filename
(string & in_name, string & out_name)
{
out_name = in_name;
if (in_name.substr(0,2) == "in")
{
out_name.replace(0,2,"out");
}
else
{
out_name.insert(0, "out.");
}
}

74
outputFileName2.cpp
...
void construct_output_filename
(string & in_name, string & out_name);

int main()
{
string input_filename, output_filename;

cout << "Enter input file name: ";


cin >> input_filename;

construct_output_filename(input_filename, output_filename);
cout << "Output file name: " << output_filename << endl;

return 0;
}

// Define function construct_output_filename here.


...

75

You might also like