strings in C language
strings in C language
strings in C language
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:
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
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[]);
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);