strings in C language

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 28

Strings

Character Strings
 A sequence of characters is often referred to as a
character “string”.
 A string is stored in an array of type char ending
with the null character '\0 '.
Character Strings
 A string containing a single character takes up 2
bytes of storage.
Character Strings
Character Strings
Character vs. String
 A string constant is a sequence of characters
enclosed in double quotes.
 For example, the character string:
char s1[2]="a"; //Takes two bytes of storage.
a \0
s1:

 On the other hand, the character, in single quotes:


char s2= `a`; //Takes only one byte of storage.
a
s2:
Character vs. String
Example

char message1[12] = "Hello world";


cout << message1 << endl;

message1: H e l l o w o r l d \0

char message2[12];
cin >> message2; // type "Hello" as input

message2: H e l l o \0 ? ? ? ? ? ?
Example : String I/O
String can be input using the extraction operator >>, but one or
more white spaces indicates the end of an input string.
char A_string[80], E_string[80];
cout << "Enter some words in a string:\n";
cin >> A_string >> E_string;
cout << A_string << E_string << “\nEND OF
OUTPUT\n";

Output:
Enter some words in a string:
This is a test.
Thisis
END OF OUTPUT
getline

 The function getline can be used to read an entire line


of input into a string variable.

 The getline function has three parameters:


 The first specifies the area into which the string is to
be read.
 The second specifies the maximum number of
characters, including the string delimiter.
 The third specifies an optional terminating character. If
not included, getline stops at ‘\n’.
Example : getline

char A_string[80];
cout << "Enter some words in a string:\n";
//80 is the size of A_string
cin.getline(A_string, 80);
cout << A_string << “\nEND OF OUTPUT\n";
Output:
Enter some words in a string:
This is a test.
This is a test.
END OF OUTPUT
Example : getline Example
char A_string[5], E_string[80];
cout << "Enter some words in a string:\n";
cin >> A_string;
cin.getline (E_string, 9) ;
cout << A_string << "#" << E_string
<< “\nEND OF OUTPUT\n";

Output:
Enter some words in a string:
This is a test.
This# is a test
END OF OUTPUT
Example : getline Example
char lastName[30], firstName[30];
cout << "Enter a name <last,first>:\n";
cin.getline (lastName, sizeof(lastName), ',');
cin.getline (firstName, sizeof(firstName));
cout << "Here is the name you typed:\n\t|"
<< firstName << " " << lastName << "|\n";

Output:
Enter a name in the form <last,first>:
Chan,Anson
Here is the name you typed:
|Anson Chan|
Ex. : String Copy Function in <cstring>
void strcpy(char dest[], const char
src[]); //copies string src into string dest
example:
char name1[16], name2[16];
strcpy(name1,"Chan Tai Man");
name1:
C h a n T a i M a n \0 ? ? ?

strcpy(name2,"999999999999999");
name2:
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 \0
strcpy(name2,name1);
name2:
C h a n T a i M a n \0 9 9 \0
Ex. 8: String Length Check Function in <cstring>
// string prototype, already included in string.h
//returns length of string(not counting'\0‘)
//you don't need to include it in your program
int strlen(const char[]);

int string_length = strlen("abcde");


//string_length is set to 5.
String Comparison
int strcmp(char s1[], char s2[]);
/*compares strings s1 and s2, returns
< 0 if s1 < s2
= 0 if s1 == s2 (i.e. strcmp returns false)
> 0 if s1 > s2
*/
int strncmp(char s1[], char s2[], int limit);
/* Same as strcmp except that at most limit characters are
compared. */
Ex. : String Comparison Examples

str1 str2 return value reason


“AAAA” “ABCD” <0 ‘A’ <‘B’
“B123” “A089” >0 ‘B’ > ‘A’
“127” “409” <0 ‘1’ < ‘4’
“abc888” “abc888” =0 equal string
“abc” “abcde” <0 str1 is a sub string of
str2
“3” “12345” >0 ‘3’ > ‘1’
Some Common Errors

 It is illegal to assign a value to a string variable


(except at declaration).
char A_string[10];
A_string = "Hello";
// illegal assignment
Should use instead
strcpy (A_string, "Hello");
Ex. : Some Common Errors

The operator == doesn't test two strings for equality.


if (string1 == string2) //wrong
cout << "Yes!";
// illegal comparison
Should use instead
if (!strcmp(string1,string2))
cout << "Yes they are same!";
//note that strcmp returns 0 (false)
if //the two strings are the same.
Manipulating Strings
Introduction
 A string is a sequence of character.

 We have used null terminated <char>


arrays (C-strings or C-style strings) to store
and manipulate strings.

 ANSI C++ provides a class called string.

 We must include <string> in our program.


Available Operations
 Creating string objects.
 Reading string objects from keyboard.
 Displaying string objects to the screen.
 Finding a substring from a string.
 Modifying string objects.
 Adding string objects.
 Accessing characters in a string.
 Obtaining the size of string.
 And many more.
Commonly Used String
Constructors
 String();
 // For creating an empty string.
 String(const char *str);
 // For creating a string object from a null-
terminated string.
Creating String Objects
 string s1, s3; // Using constructor with no arguments.
 string s2(“xyz”); // Using one-argument
constructor.
 s1 = s2; // Assigning string objects
 s3 = “abc” + s2; // Concatenating strings

 cin >> s1; // Reading from keyboard (one word)


 cout << s2; // Display the content of s2
 getline(cin, s1) // Reading from keyboard a line of text

 s3 += s1; // s3 = s3 + s1;
 s3 += “abc”; // s3 = s3 + “abc”;
Manipulating String Objects
Replacing a Substring by Another
The argument y can be: a string object, a C-style
string variable, or a double-quoted

x.replace(pos,len,y);

String strE = "12345";


strE.replace(1,2,'B'); // value is "1BB45"
Deleting (Erasing) a Substring of a
string Object

 Suppose x is a string object, and suppose


you want to delete/erase the characters in
the range [pos,pos+len) in x.
 To do so, write: x.erase(pos,len);

 The default value of len is the x.length( )


x.erase(pos); // erases x[pos..end-1]
 The default value for pos is 0
 To erase the whole string of x, do: x.clear( );
Manipulating String Objects
 string s1(“12345”);
 string s2(“abcde”);

 s1.insert(4, s2); // s1 = 1234abcde5

 s1.erase(4, 5); // s1 = 12345

You might also like