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

Understanding C-Style 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)
47 views75 pages

Understanding C-Style 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

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
[Link]
...
int main()
{
char s[] = "Hello World";

cout << s << endl;

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


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

cout << endl;


...

3
[Link]
...
char s[] = "Hello World";

cout << s << endl;

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


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

cout << endl;


...

> [Link]
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
[Link]
...
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;
...

> [Link]
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
[Link]
...
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
[Link]
cout << s << endl;

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

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

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

10
[Link]
...
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;
...

> [Link]
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
[Link]
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
[Link]
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;

> [Link]
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
[Link]
...
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++;
}

> [Link]
Hello World
HELLO WORLD

20
[Link]
...
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
[Link]
...
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;
}

> [Link]
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;
}

> [Link]
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
[Link]
#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
[Link]
#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;

> [Link]
GrouchoMarx
HarpoMarx

32
[Link]
#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
[Link]
#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;

> [Link]
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
[Link]
#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
[Link]
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;

> [Link]
Enter your first name: Groucho
Enter your last name: Marx
Your name is: Groucho Marx

38
[Link]
#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
[Link]
...
string fullName;

cout << "Enter your full name: ";


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

> [Link]
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;

> [Link]
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
[Link]
#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
[Link]
...
cout << "Enter your full name: ";
getline(cin, fullName); // <--------- Note
cout << "Your name is: " << fullName << endl;
...

> [Link]
Enter your full name: Groucho Marx
Your name is: Groucho Marx

> [Link]
Enter your full name: Groucho G. Marx III
Your name is: Groucho G. Marx III

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

> [Link]
Enter your full name: Groucho Marx
Your name is: Groucho Marx

> [Link]
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
...
[Link]
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
[Link]
if (s1 == s2)
{
cout << s1 << " equals " << s2 << endl;
}
else if (s1 < s2)
{
cout << s1 << " < " << s2 << endl;
}
else
{
cout << s1 << " > " << s2 << endl;
}

> [Link]
Enter first string: hello
Enter last string: howdy
hello < howdy

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

> [Link]
Enter first string: hello
Enter last string: Howdy
hello > Howdy

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

> [Link]
Enter first string: Hello
Enter last string: Hello World

(What will be the output?)

54
[Link]
• Blanks matter:

> [Link]
Enter first string: HelloWorld
Enter last string: Hello World
HelloWorld > Hello World

55
[Link]
...
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
[Link] (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
[Link] (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 << [Link]() << endl;

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

for (int i = 0; i < [Link](); 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 << [Link](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”);

[Link](0, 5, “Sail”);

// outputs “Sail Boat”


cout << transport << endl;

63
[Link]
// 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
[Link]
...
for (int i = 0; i < [Link](); i++)
{
if (s[i] == 's')
{
s[i] = 'z';
}
else if (s[i] == 'w')
{
s[i] = 'v';
}
else if ([Link](i, 5) == " the ")
{
[Link](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”);

[Link](0, “Happy ”);

//outputs “Happy Hippo”


cout << animal << endl;

66
[Link]
// 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
[Link]
...
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
[Link]
...
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);
for (int i = 0; i < [Link](); i++)
{
if (s[i] == '.' || s[i] == '?')
{
[Link](i, 1, ", eh?");
}
}
cout << "Canadian version: ";
cout << s << endl;
return 0;
}

69
[Link]
...
int main()
{
string s;
cout << "Enter phrase in English: ";
getline(cin, s);
for (int i = 0; i < [Link](); i++)
{
if (s[i] == '.' || s[i] == '?')
{
[Link](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
[Link]
...
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
[Link]
...
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