Strings
Strings
Strings
COMP102 Prog. Fundamentals: Strings / Slide 2
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 '.
COMP102 Prog. Fundamentals: Strings / Slide 3
Character Strings
A string containing a single character takes up 2
bytes of storage.
COMP102 Prog. Fundamentals: Strings / Slide 4
Character Strings
COMP102 Prog. Fundamentals: Strings / Slide 5
Character Strings
COMP102 Prog. Fundamentals: Strings / Slide 6
Example 1
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 ? ? ? ? ? ?
COMP102 Prog. Fundamentals: Strings / Slide 9
Output:
Enter some words in a string:
This is a test.
Thisis
END OF OUTPUT
COMP102 Prog. Fundamentals: Strings / Slide 10
getline
Example 3: 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
COMP102 Prog. Fundamentals: Strings / Slide 12
Output:
Enter some words in a string:
This is a test.
This# is a te
END OF OUTPUT
COMP102 Prog. Fundamentals: Strings / Slide 13
Output:
Enter a name in the form <last,first>:
Chan,Anson
Here is the name you typed:
|Anson Chan|
COMP102 Prog. Fundamentals: Strings / Slide 14
COMP102 Prog. Fundamentals: Strings / Slide 15
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
COMP102 Prog. Fundamentals: Strings / Slide 16
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. */
COMP102 Prog. Fundamentals: Strings / Slide 24
String Comparison
int comp102_strncmp(char s1[], char s2[],
int limit)
{
for (int i=0; i < limit; i++){
if (s1[i] < s2[i])
return -1;
if (s1[i] > s2[i])
return 1;
}
return 0;
}
COMP102 Prog. Fundamentals: Strings / Slide 25
COMP102 Prog. Fundamentals: Strings / Slide 26