String - TATI University College

advertisement
DCT1063 Programming 2
CHAPTER 3
STRINGS
Mohd Nazri Bin Ibrahim
Faculty of Computer, Media & Technology
TATi University College
nazri@tatiuc.edu.my
Strings
• In C++, a string is defined as a character
array that is terminated by a null.
• A null character is specified using '\0', and is
zero.
• For example, if you want to declare an array
str that could hold a 10-character string, you
would write:
char str[11]=“ABCDEFGHIJ”;
//Specifying the size as 11 makes room for the null at the
end of the string.
Strings(2)
•
•
C++ allows you to define a string literal.
Here are some examples:
1.
2.
3.
4.
•
•
"hello there"
"I like C++"
"#$%@@#$“
"“
The last string contains only the null
terminator, and no other characters.
It is not necessary to manually add the null
onto the end of string constants; the C++
compiler does this for you automatically.
Reading a String from the Keyboard
• The easiest way to read a string entered from
the keyboard is to make the array that will
receive the string the target of a cin
statement.
• For example, the following program reads a
string entered by the user:
• Although this program is technically correct,
there is still a problem. To see what it is,
examine the following sample run.
Enter a string: This is a test
Here is your string: This
// Using cin to read a string from the keyboard.
#include <iostream>
using namespace std;
int main()
{
char str[80];
cout << "Enter a string: ";
cin >> str; // read string from keyboard
cout << "Here is your string: ";
cout << str;
return 0;
}
Reading a String from the Keyboard(2)
• The >> operator stops reading a string when
the first whitespace character is encountered.
• Whitespace characters include spaces, tabs,
and newlines.
• One way to solve the whitespace problem is
to use another of C++’s library functions,
gets( ).
• The general form of a gets( ) call is:
gets(array-name);
Reading a String from the Keyboard(3)
• The gets( ) function will continue to read
characters until you press ENTER.
• The header used by gets( ) is <cstdio>.
• This version of the preceding program uses
gets( ) to allow the entry of strings containing
spaces.
• Now, when you run the program and enter
the string "This is a test", the entire sentence
is read and then displayed, as this sample
run shows.
Enter a string: This is a test
Here is your string: This is a test
// Using gets() to read a string from the keyboard.
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char str[80];
cout << "Enter a string: ";
gets(str); // read a string from the keyboard
cout << "Here is your string: ";
cout << str;
return 0;
}
Some String Library Functions
•
C++ supports a wide range of stringmanipulation functions. The most common
are:1.
2.
3.
4.
•
strcpy( )
strcat( )
strlen( )
strcmp( )
The string functions all use the same
header, <cstring>. Let’s take a look at these
functions now.
Some String Library Functions(2)
strcpy
– A call to strcpy( ) takes this general form:
– strcpy(to, from);
– The strcpy( ) function copies the contents of the string from
into to.
– The following program will copy "hello" into string str:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[80];
strcpy(str, "hello");
cout << str;
return 0;
}
Some String Library Functions(3)
strcat
– A call to strcat( ) takes this form:
– strcat(s1, s2);
– The strcat( ) function appends s2 to the end of s1;
s2 is unchanged.
– Both strings must be null-terminated, and the
result is null-terminated.
– The following program will print hello there on the
screen:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[20], s2[10];
strcpy(s1, "hello");
strcpy(s2, " there");
strcat(s1, s2);
cout << s1;
return 0;
}
Some String Library Functions(4)
strcmp
– A call to strcmp( ) takes this general form:
– strcmp(s1, s2);
– The strcmp( ) function compares two strings and
returns
1. 0 if they are equal.
2. Positive number if s1 is greater than s2
3. Negative number if s1 is less than s2
– The password( ) function, shown in the following
program, is a password-verification routine. It
uses strcmp( ) to check a user’s input against a
password.
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
bool password();
int main()
{
if(password()) cout << "Logged on.\n";
else cout << "Access denied.\n";
return 0;
}
// Return true if password accepted; false otherwise.
bool password()
{
char s[80];
cout << "Enter password: ";
gets(s);
if(strcmp(s, "password")) { // strings differ
cout << "Invalid password.\n";
return false;
}
// strings compared the same
return true;
}
Some String Library Functions(4)
strlen
– The general form of a call to strlen( ) is
• strlen(s);
– where s is a string.
– The strlen( ) function returns the length of the
string pointed to by s.
– Consider the following program.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
char str[80];
cout << "Enter a string: ";
gets(str);
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
char str[80];
cout << "Enter a string: ";
gets(str);
Strlen(cont)
– If the user enters the string "Hi there", this
program will display 8. The null terminator is not
counted by strlen( ).
– When the following program is run, the string
entered at the keyboard is printed in reverse. For
example, "hello" will be displayed as olleh.
// Print a string backwards.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
char str[80];
int i;
cout << "Enter a string: ";
gets(str);
// Print the string in reverse.
for(i=strlen(str)-1; i>=0; i--) cout << str[i];
return 0;
}
Some String Library Functions(5)
• As a final example, the following program
illustrates the use of all four string functions:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
char s1[80], s2[80];
cout << "Enter two strings: ";
gets(s1); gets(s2);
cout << "lengths: " << strlen(s1);
cout << ' ' << strlen(s2) << '\n';
if(!strcmp(s1, s2))
cout << "The strings are equal\n";
else cout << "not equal\n";
strcat(s1, s2);
cout << s1 << '\n';
strcpy(s1, s2);
cout << s1 << " and " << s2 << ' ';
cout << "are now the same\n";
return 0;
}
Some String Library Functions(6)
• If this program is run and the strings "hello"
and "there" are entered, then the output will
be
lengths: 5 5
not equal
hellothere
there and there are now the same
• Remember that strcmp( ) returns false if the
strings are equal. This is why you must use
the ! operator to reverse the condition, as
shown in the preceding example, if you are
testing for equality.
Using the Null Terminator
• All strings are null-terminated -can often be
used to simplify various operations.
• Example-how little code is required to
uppercase every character in a string.
• This program will print THIS IS A TEST. It
uses the library function toupper( ).
• Notice that the test condition of the for loop is
simply the array indexed by the control
variable. This works because a true value is
any non-zero value.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
// Convert a string to uppercase.
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
char str[80];
int i;
strcpy(str, "this is a test");
for(i=0; str[i]; i++) str[i] = toupper(str[i]);
cout << str;
return 0;
}
Summary
• The subscript operator, [], provides read/write
access to any element of a string.
• string member function strcmp() compares
two strings (or substrings) and returns 0 if the
strings are equal, a positive number if the first
string is lexicographically greater than the
second or a negative number if the first string
is lexicographically less than the second.
• string member functions strlen() return the
size or length of a string (i.e., the number of
characters currently stored in the string).
Download