Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
C-Strings
Computer Programming I 1
Outline
C-strings
Functions for C-strings
C-strings input
C-strings output
C-strings to numbers
Computer Programming I 2
Problems
How do I store the names of students?
How do I specify filenames?
How to I manipulate text?
Computer Programming I 3
String Taxonomy
Computer Programming I 4
An Array Type for Strings
C-strings can be used to represent strings of
characters
C-strings are stored as arrays of characters
C-strings use the null character '\0' to end a string
The Null character is a single character
To declare a C-string variable, declare an array of
characters:
char s[11];
Computer Programming I 5
Arrays
A series of elements (variables) of the same type
Placed consecutively in memory
Can be individually referenced by adding an index to
a unique name
Example, an array to contain 5 integer values of type
int called item:
int item[5];
0 1 2 3 4
item
int
Computer Programming I 6
An Array Type for Strings
C-strings can be used to represent strings of
characters
C-strings are stored as arrays of characters
C-strings use the null character '\0' to end a string
The Null character is a single character
To declare a C-string variable, declare an array of
characters:
char s[11];
Computer Programming I 7
C-string Details
Declaring a C-string as char s[10] creates
space for only nine characters
The null character terminator requires one space
A C-string variable does not need a size
variable
The null character(‘\0’) immediately follows the last
character of the string
Example:
s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
H i M o m ! \0 ? ?
Computer Programming I 8
C-string Declaration
To declare a C-string variable, use the
syntax:
Computer Programming I 9
Initializing a C-string
To initialize a C-string during declaration:
char my_message[20] = "Hi there.";
The null character '\0' is added for you
Another alternative:
char short_string[ ] = "abc";
but not this:
char short_string[ ] = {'a', 'b', 'c'};
Computer Programming I 10
C-string error
This attempt to initialize a C-string does
not cause the ‘\0’ to be inserted in the
array
char short_string[ ] = {'a', 'b', 'c'};
Computer Programming I 11
C-style string A C-style string in C++ is
The declaration: basically an array of
characters, terminated by a
char name[10]="Hello";
null character ('\0')
H e l l o \0
Computer Programming I 12
The declaration:
char name[]={'H','e','l','l','o','\0'};
H e l l o \0
Computer Programming I 13
The declaration: The declaration:
is equivalent is equivalent
H \0 H \0
(the size of the array is 6, (the size of the array is 2,
But the length of the string is 1) But the length of the string is 1)
Computer Programming I 14
Null string
The declaration: (empty string) The declaration:
is equivalent is equivalent
\0 \0
(the size of the array is 1, (the size of the array is 1,
the length of the string is 0) the length of the string is 0)
Computer Programming I 15
The declaration:
char name[]="H";
H \0
(the size of the array is 2,
is NOT equivalent the length of the string is 1)
char name='H'; H
(this is not an array nor a string,
it is simply a character)
Computer Programming I 16
char name[11]="John Connor";
J o h n C o n n o r
Computer Programming I 17
Assignment With C-strings
This statement is illegal:
a_string = "Hello";
This is an assignment statement, not an
initialization
The assignment operator does not work
with C-strings
Computer Programming I 18
Assignment of C-strings
A common method to assign a value to a
C-string variable is to use strcpy, defined in
the cstring library
Example: #include <cstring>
…
char a_string[ 11];
strcpy (a_string, "Hello");
Computer Programming I 19
#include <iostream>
#include <cstring> strcpy()
using namespace std;
int main() {
char source[] = "Judgement Day"; Copy one string into
char dest[] = "Rise of the Machine";
another. Copy string
strncpy(dest,source);
source to dest,
cout << "source = " << source << endl;
cout << " dest = " << dest << endl; stopping after the
} terminating null
character has been
moved.
source = Judgement Day
dest = Judgement Day
dest = source;
. . .
}
Computer Programming I 21
int main() { This is an initialization, it
char dest[20] = "Judgement Day";
}
is valid.
Computer Programming I 22
A Problem With strcpy
strcpy can create problems if not used
carefully
strcpy does not check the declared length
of the first argument
Computer Programming I 23
A Solution for strcpy
Many versions of C++ have a safer version of
strcpy named strncpy
strncpy uses a third argument representing the
maximum number of characters to copy
Example: char another_string[10];
strncpy(another_string,
a_string_variable, 9);
Computer Programming I 24
== Alternative for C-strings
The = = operator does not work as expected with
C-strings
The predefined function strcmp is used to compare C-
string variables
Example: #include <cstring>
…
if (strcmp(c_string1, c_string2))
cout << "Strings are not the same.";
else
cout << "String are the same.";
Computer Programming I 25
strcmp's logic
strcmp compares the numeric codes of
elements in the C-strings a character at a
time
If the two C-strings are the same, strcmp returns 0
0 is interpreted as false
As soon as the characters do not match
strcmp returns a negative value if the numeric code in the
first parameter is less
strcmp returns a positive value if the numeric code in the
second parameter is less
Non-zero values are interpreted as true
Computer Programming I 26
#include <iostream>
#include <cstring> strcmp()
using namespace std; Compare one string to another starting
int main() { with the first character in each string and
char string1[] = "Hello"; continuing with subsequent characters
char string2[] = "Hello World"; until the corresponding characters differ
char string3[] = "Hello World"; or until the end of the strings is reached.
char string4[] = "Aloha";
int n;
n = strcmp(string1, string2);
cout << string1 << "\t\t" << string2 << "\t==> " << n << endl;
Hello Hello World ==> -1
n = strcmp(string2, string3);
cout << string2 << '\t' << string3 << "\t==> " << n << endl;
Hello World Hello World ==> 0
n = strcmp(string3, string4);
cout << string3 << '\t' << string4 << "\t\t==> " << n << endl;
}
Hello World Aloha ==> 1
Computer Programming I 27
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char string1[] = "Hello";
char string2[] = "Hello";
if ( string1==string2 )
cout << "Same"; output:
else Different
cout << "Different";
}
Computer Programming I 28
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char string1[] = "Hello";
char string2[] = "Hello";
if (strcmp(string1,string2)==0 )
cout << "Same"; output:
else Same
cout << "Different";
}
Computer Programming I 29
More C-string Functions
The cstring library includes other functions
strlen returns the number of characters in a string
int x = strlen( a_string);
strcat concatenates two C-strings
The second argument is added to the end of the first
The result is placed in the first argument
Example:
char string_var[20] = "The rain";
strcat(string_var, "in Spain");
Computer Programming I 30
The strncat Function
strncat is a safer version of strcat
A third parameter specifies a limit for the
number of characters to concatenate
Example:
char string_var[20] = "The rain";
strncat(string_var, "in Spain", 11);
Computer Programming I 31
#include <iostream>
#include <cstring>
strcat()
using namespace std;
int main() {
char dest[30] = "Rise of "; Appends one string to
char source[] = "The Machine"; another. strcat()
appends a copy of
strcat( dest, source ); source to the end of
cout << " dest = " << dest << endl; dest. The length of
cout << "source = " << source << endl; the resulting string is
}
strlen(dest) +
dest = Rise of The Machine strlen(source).
source = The Machine
Computer Programming I 32
char s1[12]="Hello";
char s2[]="World";
s1 s2
H e l l o \0 W o r l d \0
strcat(s1,s2);
s1 s2
H e l l o W o r l d \0 W o r l d \0
Computer Programming I 33
C-String functions in C's
Standard Library
Must #include <cstring>
Most common functions:
strlen() – get the length of the string without counting the
terminating null character.
strncpy() - copy one string to another string
strcmp() - compare two string
strncat() - concatenates / join two string
Computer Programming I 34
C-string Output
C-strings can be output with the
insertion operator
Example: char news[ ] = "C-strings";
cout << news << " Wow."
<< endl;
Computer Programming I 35
C-string Input
The extraction operator >> can fill a C-
string
Whitespace ends reading of data
Example: char a[80], b[80];
cout << "Enter input: " << endl;
cin >> a >> b;
cout << a << b << "End of Output";
could produce:
Enter input:
Do be do to you!
DobeEnd of Output
Computer Programming I 36
Simple C-String Input and Output
must #include this for using
Consider this program : strlen() function
int main()
{ To treat the array of characters as C-
char name[10]; string, we just use the name of the
cout << "Name => ";
array when dealing with I/O stream.
cin >> name;
cout << "Name is [" << name << "]" << endl;
Computer Programming I 37
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char name[10];
cout << "Name => ";
cin >> name;
cout << "Name is [“ << name << "]\n";
cout << "Name length is “ << strlen(name);
}
Computer Programming I 38
Reading an Entire Line
Predefined member function getline can
read an entire line, including spaces
getline is a member of all input streams
getline has two arguments
The first is a C-string variable to receive input
The second is an integer, usually the size of the
first argument specifying the maximum number
of elements in the first argument getline is
allowed to fill
Computer Programming I 39
Using getline
The following code is used to read an entire
line
including spaces into a single C-string
variable
char a[80];
cout << "Enter input:\n";
cin.getline(a, 80);
cout << a << End Of Output\n";
and could produce:
Enter some input:
Do be do to you!
Do be do to you!End of Output
Computer Programming I 40
getline syntax
Syntax for using getline is
Computer Programming I 41
More C-String Input and Output
Sample run:
consider:
Name => HelloThereHowAreYou
#include <cstring> Name is [HelloThereHowAreYou]
#include <iostream> Name length is 19
using namespace std;
int main() {
char name[10];
cout << "Name => ";
cin >> name;
cout << "Name is [“ << name << "]\n";
cout << “The Length: “ << strlen(name);
}
Computer Programming I 43
#include <iostream> sample run 1:
using namespace std; same as
alibabamuthu
before
int main () { [alibabamu]
char name[20];
cin.get(name,10,'z'); sample run 2: user press
enter, '\n'
cout << "[" << name << "]"; ali
is read as
baba
} muthu
valid input
since '\n' is
[ali
NOT the
baba
delimiter.
]
the character 'z' is used
as delimiter the delimiter
sample run 3: (which is 'z' in this
afizuddin case) is encounter,
[afi] thus stop reading
Computer Programming I 44
#include <iostream>
using namespace std;
int main () { output:
char name[20]; ab cde
cin >> name; [ab]
cout << "[" << name << "]";
}
#include <iostream>
using namespace std; output:
int main () {
ab cde
char name[20]; [ab cde]
cin.get(name,10);
cout << "[" << name << "]";
}
Computer Programming I 45
Input functions : overcome delimiter problem using cin.getline(...)
#include <iostream>
using namespace std; sample run 1:
int main () { mary
[mary] This
char name1[10],name2[10],name3[10]; peter solved the
cin.getline(name1,10); [peter] delimiter
john
cout << "[" << name1 << "]\n"; [john]
problem!!
cin.getline(name2,10);
cout << "[" << name2 << "]\n";
cin.getline(name3,10);
cout << "[" << name3 << "]\n";
}
Computer Programming I 46
#include <iostream>
using namespace std; sample run 1:
int main () { marypeter
[mary]
char name1[10],name2[10],name3[10]; pan
cin.getline(name1,10,'p'); john
[eter
cout << "[" << name1 << "]\n"; pan
cin.getline(name2,10,'j'); ]
cout << "[" << name2 << "]\n"; carl
[ohn
cin.getline(name3,10,'a'); c]
cout << "[" << name3 << "]\n";
} Why?
Computer Programming I 47
Assigning Characters Into C-Strings
#include <cstring>
#include <iostream> Strings are treated just
using namespace std;
like an array of
int main() {
character values here.
char str[11]; The null character is
str[0] = 'H'; str[1] = 'I'; str[2] = '\0'; used to indicate the
cout << str << endl;
end of the string when
for (int i=0; i<=9; i++) str[i] = 'A' + i; processed by the
str[i] = '\0'; standard library such
cout << str << endl; as puts() function.
str[5] = '\0';
for (int i=0; i<=10; i++)
cout << "[" << static_cast<int>( str[i] ) << "]"; output:
cout << endl;
cout << str << endl; HI
ABCDEFGHIJ
str[5] = 'A'; [65][66][67][68][69][0][71][72][73][74][0]
cout << str << endl; ABCDE
system("pause");
ABCDEAGHIJ
}
Computer Programming I 48
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char dest[30] = "Rise of ";
char source[] = "The Machine";
Computer Programming I 49
Array of C-Strings
The declaration:
declares one string of which the maximum
length is 29.
char actor[30];
A c-string is an one-dimensional array of
characters.
one solution:
This declare an array of 5 strings, of which
char actor[5][30]; the maximum length of the string is 30.
That means, an array of strings is actually
a two-dimensional array of characters.
Computer Programming I 50
char actor[4][10] = { "Arnold",
"Nick",
"Claire",
"Kristanna" };
0 1 2 3 4 5 6 7 8 9
actor[0] A r n o l d \0
actor[1] N i c k \0
actor[2] C l a i r e \0
actor[3] K r i s t a n n a \0
Computer Programming I 51
Example:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char actor[4][30] = { "Sylvester Stallon",
"Nick Stahl", "Claire Danes" };
char anotherActor[30] = "Arnold Schwarzenegger";
Computer Programming I 53
C-strings to Integers
To read an integer as characters
Read input as characters into a C-string, removing
unwanted characters
Use the predefined function atoi to convert the
C-string to an int value
Computer Programming I 54
C-string to long
Computer Programming I 55
C-string to double
C-strings can be converted to type
double using the predefined function
atof
atof returns a value of type double
Example: atof("9.99") returns 9.99
atof("$9.99") returns 0.0
because the $ is not a digit
Computer Programming I 56
Library cstdlib
The conversion functions
atoi
atol
atof
are found in the library cstdlib
To use the functions use the include
directive
#include <cstdlib>
Computer Programming I 57
C-String conversion to numbers
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[] = "1234"; char str2[] = "0123"; char str3[] = " 123";
char str4[] = "$123"; char str5[] = "12.34";
int n1,n2,n3,n4,n5; double d1,d2,d3,d4,d5; long l1,l2,l3,l4,l5;
n1 = atoi(str1); n2 = atoi(str2); n3 = atoi(str3);
n4 = atoi(str4); n5 = atoi(str5);
d1 = atof(str1); d2 = atof(str2); d3 = atof(str3);
d4 = atof(str4); d5 = atof(str5);
l1 = atol(str1); l2 = atol(str2); l3 = atol(str3);
l4 = atol(str4); l5 = atol(str5);
cout << n1 << " " << n2 << " " << n3 << " " << n4 << " " << n5 << endl;
cout << d1 << " " << d2 << " " << d3 << " " << d4 << " " << d5 << endl;
cout << l1 << " " << l2 << " " << l3 << " " << l4 << " " << l5 << endl;
}
Computer Programming I 58
Predefined Functions
toupper(char_exp) – convert lowercase character to uppercase
tolower(char_exp) – convert uppercase character to lowercase
Computer Programming I 59
Predefined Functions (cont.)
atoi(str_exp) ingr1 = atoi(str1);
Parses string interpreting its content as a number and
returns an int value
Computer Programming I 60
The End
Computer Programming I 61