Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Chapter 3 Strings in c++ programming

This document provides an overview of C++ strings, including character types, string declaration, initialization, and manipulation using various functions from the string and cstring libraries. It explains how to read, concatenate, and compare strings, as well as the significance of the NULL character in string termination. Additionally, it includes code examples demonstrating string operations in C++.

Uploaded by

dhfsgf6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 3 Strings in c++ programming

This document provides an overview of C++ strings, including character types, string declaration, initialization, and manipulation using various functions from the string and cstring libraries. It explains how to read, concatenate, and compare strings, as well as the significance of the NULL character in string termination. Additionally, it includes code examples demonstrating string operations in C++.

Uploaded by

dhfsgf6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Chapter 3

C++ Strings

Compiled By Dagne Walle 1


Characters and Literals Strings

• Char in C++ is normally an 8-bit quantity, whereas in


Java it is a 16-bit value.
• Char can be declared either as signed or unsigned.
• wchar_t represents a wide character, 16-bit character.
• NULL Character is also known as string terminating
character.
• It is represented by “\0”.
• NULL Character is having ASCII value 0

Compiled By Dagne Walle 2


Strings in C++

• A string is nothing but the collection of the


individual array elements or characters.
• String is enclosed within Double quotes.
• “programming" is a example of String.
• Each Character Occupy 1 byte of Memory.
• Size of “programming“ = 11 bytes
• String is always Terminated with NULL Character
(‘\0′).
• char word[20] = “‘p’ , ‘r’ , ‘o’ , ‘g’ , ‘r’ , ‘a’ , ‘m’ ,
‘m’ , ‘I’ , ‘n’ , ‘g’ , ‘\0’”
3
Compiled By Dagne Walle
Strings in C++ Programs
• String library <string> or <cstring> provides
functions to:
- manipulate strings
- compare strings
- search strings

• ASCII character code


- Strings are compared using their character codes
- Easy to make comparisons (greater than, less than,
equal to)
Compiled By Dagne Walle 4
Strings in C++ Programs
• Character Constant
- Integer value of a character
- Represented with single quotes
- ‘z’ is the integer value of z, which is 122
• String in C++
- Series of characters treated as one unit
- can include letters, digits, special characters +, -, *,

- String literal (string constants) enclosed in double
quotes, for example: “C++ course”

Compiled By Dagne Walle 5


Strings in C++ Programs
Example:
Write a C++ program that reads first and the last name
of a person and displays a personalized message to the
program user.
Analysis stage:
- Input:
Dagne for the first name
Walle for the last name
-Output:
Dagne Walle
Compiled By Dagne Walle 6
Declaration of a Character String
• we use array of type “char” to create String.

• Syntax :

• char char_Variable_name [ SIZE ] ;

• Examples :

• char city[30];

• char name[20];

• char message[50];

Compiled By Dagne Walle 8


Initializing String (Character Array)
• Process of Assigning some legal default data to String is
Called Initialization of String.
• A string can be initialized in different ways. We will explain
this with the help of an example.
• Below is an example to declare a string with name as str and
initialize it with “Ethiopia”.
1. char str[] = " Ethiopia";
2. char str[50] = " Ethiopia ";
3. char str[] = {‘E’,’t',’h',’i',’o',’p',’i',’a’ '\0'};
4. char str[14] = {‘E’,’t',’h',’i',’o',’p',’i',’a’ '\0'}; 9
Compiled By Dagne Walle
C ++ Strings
– Formatted Input: Stream extraction operator
• cin >> stringObject;
• the extraction operator >> formats the data that it receives
through its input stream; it skips over whitespace

– Unformatted Input: getline function for a string


• getline( cin, s)
– does not skip over whitespace
– delimited by newline
– reads an entire line of characters into s
string s = “ABCDEFG”;
getline(cin, s); //reads entire line of characters into s
char c = s[2]; //assigns ‘C’ to c
S[4] = ‘*’; //changes s to “ABCD*FG”
10
Compiled By Dagne Walle
UsingStrings
Strings in
inC++
C++Programs .. Cont.
Programs
//A program to display a user’s name with a welcome message
#include <iostream>
#include <string>
using namespace std;
void main ( )
{ string first_name; // first name declaration
string last_name; // first name declaration
cout<<"Enter first name " ;
cin >> first_name;
cout<<"Enter first name " ;
cin>> last_name;
cout<< "Hello "<< first_name << “ " << last_name <<endl;
}
Compiled By Dagne Walle 11
Strings inbuild
Using C++ Programs
in library.

#include <iostream>
#include <string>
using namespace std;
void main ()
{string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
str3 = str1; // copy str1 into str3
cout << "str3 : " << str3 << endl;
// concatenates str1 and str2
str3 = str1 + str2;
cout << "str3 : " << str3 << endl;
len = str3.size();
cout << "str3.size() : " << len <<endl; 12
Compiled By Dagne Walle
}
Strings in C++ Programs
Output :

Compiled By Dagne Walle 13


Character Literals and the cctype Library

isalpha(c) True if c is alphabetic


isupper(c) True if c is upper case
islower(c) True if c is lower case
isdigit(c) True if c is decimal digit char
isxdigit(c) True if c is hexidecimal digit
isalnum(c) True if c is alphabetic or numeric
isspace(c) True if c is whitespace (space, tab or newline)
isprint(c) True if c is a printable character (8 bit only)

Compiled By Dagne Walle 14


String Literals

• A literal string value has type array of character


in C++, whereas it has type string in Java.
• Always remember the null character at the end of
a string literal.

Compiled By Dagne Walle 15


The cstring Library
• defined by header file string.h, should not be confused with the
header file string.

strcpy(dest, src) Copy characters from source to destination


strncpy(dest, src, n) Copy exactly n characters
strcat(dest, src) Append characters from source onto destination
strncat(dest, src, n) Append only n characters
strcmp(s1, s2) Compare strings s1 and s2
strncmp(s1, s2, n) Compare first n characters in s1 and s2
strlen(s) Count number of characters in s

Compiled By Dagne Walle 16


Strings in C++
- String can be array of characters ends with null character ‘\0’.
char color [ ] = “green” ;
-- this creates 6 element char array, color, (last element
is ‘\0’)

g r e e n \0

color can be declared also as :


char color [ ] = {‘g’, ‘r’, ‘e’, ‘e’, ‘n’, ‘\0’ };
char color [ 6] = {‘g’, ‘r’, ‘e’, ‘e’, ‘n’, ‘\0’ };

Compiled By Dagne Walle 17


Strings in C++
• Reading Strings
- Assign input to character array, for example
char word [ 20 ];
cin >> word;
cout<<word<<endl;
-- this reads characters until a space, tab, newline,
or end-of-file is encountered.
-- the string should be less than 19 characters, the
20th is for the null character (‘\0’).
Problem: read characters until the first white space
Compiled By Dagne Walle 18
C ++ Strings
Creating String Objects

#include <string> string type in the


//string initialization <string> header file.

string s; //s contains 0 characters


string s1( "Hello" ); //s1 contains 5 characters
string s2 = “Hello”; //s2 contains 5 characters
//implicitly calls the constructor

string s3( 8, 'x' ); //s3 contains 8 'x' characters


string s4 = s3; //s4 contains 8 'x' characters

string s5(s2, 3, 2); //s5 copies a substring of s2; it contains ”lo”


Compiled By Dagne Walle 19
Functions of string.h
Function Purpose Example Output

Strcpy(); Makes a copy of a strcpy(s1, Copies “Hi” to ‘s1’


string “Hi”); variable
Strcat(); Appends a string to strcat(“Work”, Prints
the end of “Hard”); “WorkHard”
another string
Strcmp(); Compare two strcmp(“hi”, Returns -1.
strings “bye”);
alphabeticall
y
Strlen(); Returns the strlen(“Hi”); Returns 2.
number of
characters in a
string
Strrev(); reverses a given Strrev(“Hell olleH
string o”);
Strlwr(); Converts string to Strlwr(“HELL hello
lowercase O”);
Strupr(); Converts string to Strupr(“hello”); HELLO
uppercase 20
Functions of Functions
cstring.h of cstring
Function Description
char *strcpy(char *s1, const char *s2); Copies string s2 into the
character array s1. The
value of s1 is returned.
char *strncpy(char *s1, const char *s2, size_t n); Copies at most n
characters of string s2
into the array s1. The
value of s1 is returned.
char *strcat (char *s1, const char *s2); Appends string s2 to
string s1. The value of s1
is returned.
char *strncat (char *s1, const char *s2, size_t n); Appends at most n
characters of string s2 to
string s1. The value of s1
is returned.

Compiled By Dagne Walle 21


Functions of cstring.h
int strcmp(const char *s1, const char *s2); Compares string s1
with string s2. The
function returns a value
of zero, less than zero
or greater than zero if
s1 is equal to, less than
or greater than s2,
respectively.
int strncmp(const char *s1, const char *s2, size_t Compares up to n
n); characters of string s1
with string s2. The
function returns zero,
less than zero or greater
than zero if s1 is equal
to, less than or greater
than s2, respectively.
22
Compiled By Dagne Walle
String Copy (strcpy)
• strcpy( ) function copies contents of one string into another string.
• Syntax : strcpy (destination_string , source_string );
• Example:-strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
• If destination string length is less than source string, entire source
string value won’t be copied into destination string. For example,
consider destination string length is 20 and source string length is
30. Then, only 20 characters from source string will be
copied into destination string and remaining 10 characters
won’t be copied and will be truncated. 23
Compiled By Dagne Walle
String Copy (strcpy)

- strcpy(s1, s2) → s1 = s2 Copies string s2 into string s1.

#include <iostream>
#include <cstring>
using namespace std;
void main() {
char str1[] =“Dagne";
char *str2 = “Girmaw";

strcpy(str1,str2);

cout<<str1<<endl;
}
Compiled By Dagne Walle 24
String Copy (strncpy)
strncpy(s1, s2) → s1[n] = s2[n]

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

void main() {
char str1[] = ”Dagne";
char *str2 = “Walle Girmaw";

strncpy(str1,str2,5);

cout<<str1<<endl;
}
Compiled By Dagne Walle 25
String Concat (strcat)
• strncat( ) function in C language concatenates (appends) portion
of one string at the end of another string.
• Syntax : strncat ( destination_string , source_string, size);
• Example:-strncat ( str2, str1, 3 ); – First 3 characters of str1 is
concatenated at the end of str2.
• As you know, each string in C is ended up with null character
(‘\0’).
• In strncat( ) operation, null character of destination string is
overwritten by source string’s first character and null character is
added at the end of new destination string which is created after
strncat( ) operation.

Compiled By Dagne Walle 26


C ++ Strings
String Objects

You can also concatenate C++ strings using the + and += operators:

string s = “ABCD*FG”;
string s2 = “Robot”;
string s5 = “Soccer”;
string s6 = s + “HIJK”; //changes s6 to “ABCD*FGHIJK

s2 += s5; //changes s2 to “RobotSoccer”

Compiled By Dagne Walle 27


String concatenation
• Concatenation
– s3=“Dagne”
– s3.append( “Walle" );
– s3 += “Girmaw";
• Both add "pet" to end of s3
– s3.append( s1, start, N );
• Appends N characters from s1, beginning at index
start

Compiled By Dagne Walle 28


String Concat (strcat)
strcat(s1, s2) → s1 = s1+s2
Concatenates string s2 onto the end of string s1.
#include <iostream>
#include <cstring>
using namespace std;

void main() {
char str1[24] = ”Haramaya";
char *str2 = “University";
strcat(str1,str2);
cout<<str1<<endl;
}

Compiled By Dagne Walle 29


String Concat (strncat)
strncat(s1, s2,n) → s1 = s1+s2[n]

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

void main() {
char str1[24] = ”Haramaya";
char *str2 = “University of Ethiopia";

strncat(str1,str2,10);

cout<<str1<<endl;
}

Compiled By Dagne Walle 30


String Compare (strcmp)
➢ strcmp( ) function in C compares two given strings and returns
zero if they are same.
➢ If length of string1 < string2, it returns < 0 value that is -1.

✓ If length of string1 > string2, it returns > 0 value that is 1

✓ If length of string1 = string2 it returns 0.

Syntax : strcmp (str1 , str2 );strcmp( ) function is case sensitive. i.e,


“A” and “a” are treated as different characters.

Compiled By Dagne Walle 31


String Compare (strcmp)
strcmp(s1, s2) → 0 if s1 = s2
→ -1 if s1 < s2
#include <iostream> → 1 if s1 > s2
#include <cstring>
using namespace std;
void main() {
char str1[20]; char str2[20] ; cin.getline(str1,20);
cin.getline(str2,20);
if (strcmp(str1,str2))
if (strcmp(str1,str2) == 1)
cout<<str1<<" > "<<str2<<endl;
else
cout<<str1<<" < "<<str2<<endl;
else 32
cout<<str1<<" = "<<str2<<endl; Compiled By Dagne Walle
String Compare (strncmp)
strncmp(s1, s2,n) → 0 if s1[n] = s2[n]
#include <iostream> → -1 if s1[n] < s2[n]
#include <cstring> → 1 if s1[n] > s2[n]
using namespace std;
void main() {
char str1[20] ; char str2[20] ; cin.getline(str1,20);
cin.getline(str2,20);
if (strncmp(str1,str2,1))
if (strcmp(str1,str2,1) == 1)
cout<<str1<<" > "<<str2<<endl;
else
cout<<str1<<" < "<<str2<<endl;
else
cout<<str1<<" = "<<str2<<endl; }
33
Compiled By Dagne Walle
String Length (strlen)
• strlen( ) function in C gives the length of the given
string.

• Syntax : strlen(str);

• strlen( ) function counts the number of characters in a given


string and returns the integer value.

• It stops counting the character when null character is found.


Because, null character indicates the end of the string in C.

Compiled By Dagne Walle 34


C ++ Strings
String Objects

The C++ string class also defines a length() function for extracting
how many characters are stored in a string.

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

Prints 4 for the string s = “Leon”

You can also use the subscript operator [ ] to access


individual characters:
e.g. s[0] = ‘N’ ; //where index: 0 to length-1
Compiled By Dagne Walle 35
String Length (strlen)
strlen(s) → How many characters in s.
- is a function that accepts a string, defined as an array of
characters, and returns the number of characters in the string
excluding null character
#include <iostream>
#include <cstring>
using namespace std;
void main() {
char s1[] = “Haramaya University";
char *s2 = “Harar";
cout<<s1<<" Consists of "<<strlen(s1)<<" Characters.\n";
cout<<s2<<" Consists of "<<strlen(s2)<<" Characters.\n";
}
Compiled By Dagne Walle 36
C ++ Strings
String Objects

C++ strings can be converted to C-strings:

string s = “ABCDEFG”;
const char* cs = s.c_str();

Converts s into the C-string cs.

The c_str() function has a return type const char*

Compiled By Dagne Walle 37


C ++ Strings
String Objects

Substring function: substr()

s6 = “ABCD*FGHIJK”;
s4 = s6.substr(5, 3); //changes s4 to “FGH”

s4 gets a substring of s6, starting at index 5 and taking 3


characters

Compiled By Dagne Walle 38


C ++ Strings
Substrings

• Function substr gets a substring

– s1.substr( start index, N );


– gets N characters, beginning with index start
– returns substring

Compiled By Dagne Walle 39


C ++ Strings
String Objects

erase() and replace() functions:

s6 = “ABCD*FGHIJK”;
s6.erase(4, 2); //changes s6 to “ABCDGHIJK”;

s6.replace(5, 2, “xyz”); //changes s6 to “ABCDGxyzJK”;

replace 2 characters from s6, starting at


index 5, with “xyz”

Compiled By Dagne Walle 40


C ++ Strings
String Objects

find() function
returns the index of the first occurrence of a given substring:

string s7 = “Mississippi River basin”; //23 characters


cout << s7.find(“si”) << endl; //prints 3
cout << s7.find(“so”) << endl; //prints 23, the length of the string

If the find() function fails, it returns the


length of the string it was searching.

i.e. find() returns 4,294,967,295


Compiled By Dagne Walle 41
Strings Assignment in C++
• Assignment
– s2 = s1;
• Makes a separate copy
– s2.assign(s1);
• Same as s2 = s1;
– myString.assign(s, start, N);
• Copies N characters from s, beginning at index start
– Individual character assignment
• s2[0] = s3[2];

Compiled By Dagne Walle 42


StringsComparing strings in C++
comparison
• Overloaded operators
– ==, !=, <, >, <= and >=
– returns bool
• s1.compare(s2)
– returns positive if s1 is lexicographically greater
• compares letter by letter
• 'B' lexicographically greater than 'A‘
• ‘a’ lexicographically greater than ‘A‘
• ‘a’ lexicographically greater than ‘Z‘
– returns negative if less; zero if equal
• Sample order: ‘A’,”Apple”, “Banana”, “Zest”, ‘a’, “apricot”, “leon”

– s1.compare(start, length, s2, start, length)


• Compare portions of s1 and s2
– s1.compare(start, length, s2)
• Compare portion of s1 with all of s2
Compiled By Dagne Walle 43
Strings Swapping in C++

Swapping strings

• s1.swap(s2);
– Switch contents of two strings

Compiled By Dagne Walle 44


Strings Characteristic in
string Characteristics C++
• Member functions
– s1.size() and s1.length()
• Number of characters in a string
– s1.capacity()
• Number of elements that can be stored without
reallocation
– s1.max_size()
• Maximum possible string size
– s1.empty()
• Returns true if empty
– s1.resize(newlength)
• Resizes string to newlength
Compiled By Dagne Walle 45
Finding Strings
Finding and
Strings andCharacters
Characters inin a string
a string
• Find functions
– If found, index returned
– If not found, string::npos returned
– s1.find( s2 )
– s1.rfind( s2 )
• Searches right-to-left
– s1.find_first_of( s2 )
• Returns first occurrence of any character in s2
• Example: s1.find_first_of( "abcd" )
– Returns index of first 'a', 'b', 'c' or 'd'

Compiled By Dagne Walle 46


Finding Strings and Characters in a string

• Find functions
– s1.find_last_of( s2 )
• Finds last occurrence of any character in s2
– s1.find_first_not_of( s2 )
• Finds first character NOT in s2
– s1.find_last_not_of( s2 )
• Finds last character NOT in s2

Compiled By Dagne Walle 47


Replacing Characters in a string
• s1.erase( start )
– Erase from index start to end of string, including
start
• Replace
– s1.replace( begin, N, s2)
• begin: index in s1 to start replacing
• N: number of characters to replace
• s2: replacement string
– s1.replace( begin, N, s2, index, num )
• index: element in s2 where replacement comes from
• num: number of elements to use when replacing
– Replace can overwrite characters
Compiled By Dagne Walle 48
Replacing Characters
Example in a string
s1.replace( begin, N, s2, index, num )

• begin: index in s1 to start replacing


• N: number of characters to replace
• s2: replacement string
• index: element in s2 where replacement comes from
• num: number of elements to use when replacing

string str = "this is an example string.";


string str3="sample phrase";

str.replace(19,6, str3, 7, 6); // "this is an example phrase."

Compiled By Dagne Walle 49


Inserting Characters into a string

• s1.insert( index, s2 )
– Inserts s2 before position index
• s1.insert( index, s2, index2, N );
– Inserts substring of s2 before position index
– Substring is N characters, starting at index2

Compiled By Dagne Walle 50


Warning!
• No conversion from int or char

– The following definitions could return errors, or


warnings only, but then would cause the program to
crash afterwards

• string error1 = 'c';


• string error2( 'u' );
• string error3 = 22;
• string error4( 8 );

– However, it can be assigned one char after its


declaration:
• s = 'n'; Compiled By Dagne Walle 51
Table 1 Comparison of string functionality in C++ and Java
Operation C++ Java
Number of length () String.length()
Characters
Readjust length resize (newsize, pad) StringBuffer.setLength(newsize
)
Assign s = s2
Append s +=s2 StringBuffer.apend(s2)
Catenation s + s2 String.concat(s2)
Character access s[index] String.charAt(index)
Insertion insert(location, s2) StringBuffer.insert(location, s2)
Removal remove(location, length)
Replacement replace(location, length, s2)
Substring substring(location, length) String.substring(start, end)
Comparison S < s2
Comparison strcmp(s.c_str, s2.c_str) String.compareTo(s2)
Equality comparison s == s2 Compiled By Dagne Walle
String.equals(s2)
Substring search find(text, start) String.indexOf(s2)
Character search find_first_of(text, start)
52
THANK YOU

Compiled By Dagne Walle 53

You might also like