C-strings
C-strings
Ye
C++ Strings
3
Initializing a C-string
• You may initialize the C-string character by character after it
is declared (Remember to include the null character!)
• More often, initialize a C-string during declaration:
char my_message[20] = "Hi there.";
• Another alternative:
char short_string[] = "abc";
• For each of the above, the null character is automatically
added for you
• but not this -- ‘\0’ is not inserted in this array:
char short_string[] = {'a','b','c'};
4
Don't Change '\0'
• “size” variable may not be needed when processing C-strings
– Just use the null character
int index = 0;
while (our_string[index] != '\0')
{
our_string[index] = 'X';
index++;
}
• The termination of the loop depends on the null character!
int index = 0;
while(our_string[index] != '\0‘ && index < SIZE)
{
our_string[index] = 'X';
index++;
}
6
Library
• Declaring c-strings
– Requires no C++ library
– Built into standard C++
7
C-string Arguments and Parameters
• Recall: c-string is array
• Like all arrays, you may send size into functions as well
– Function could also use ‘\0’ to find end, or use strlen
– So size parameter is not a must in most cases
– Use "const" modifier to protect c-string arguments when
applicable
8
C-string Functions: strlen
• Defined in <cstring> library
9
= and == with C-strings
• Recall: C-string is array!
• C-string variable cannot be assigned:
char aString[10];
aString = "Hello"; // illegal!
• Can ONLY use "=" at declaration of the C-string!
E.g.
char news[] = “Earthquake!”;
cout << news << endl << “When?”;
14
C-String Input
• Whitespace is "delimiter"
– Tab, space, line breaks are "skipped"
– Input reading "stops" at delimiter
15
C-String Input Example
char s1[80], s2[80];
cout << "Enter input: ";
cin >> s1 >> s2;
cout << s1 << s2 << "END OF OUTPUT\n";
• Sample run:
Enter input: Do be do to you!
DobeEND OF OUTPUT
– Underlined portion is user input
– C-string s1 receives “Do"
– C-string s2 receives "be"
16
C-String Line Input
– Dialogue:
Enter input: Do be do to you!
Do be do to you!END OF OUTPUT
17
The Standard string Class