CS计算机代考程序代写 c++ Character and String

Character and String

Computer Programming

Character data type

2

! Written between single quotes, length must be one:
‘A’, ‘b’, ‘*’

! In C++, a char type variable is internally represented
as a 8-bit integer, according to the ASCII table

! Therefore a char can also be used & printed as
integer (with type casting)

! Example:
cout << 'a'; /* a is printed */ cout << (int)'a'; /* 97 is printed */ cout << (char)97; /* a is printed */ ASCII Table 3 Example: ASCII value of character '7' is 55 but not 7! char features 4 A B ... Z ... a b ... z 65 66 ... 90 .. 97 98 ... 122 'a' + 1 has the value of 'b', 'b' + 1 has the value of 'c', ... test if character c is lower-case letter: if ('a' <= c && c <= 'z') ... (recommended) same as: if (97 <=c && c <= 122) ... (not recommended) If the variable c has the value of a lowercase letter, then the expression c + 'A' – 'a' /* same as c + (65 -97)*/ has the value of the corresponding uppercase letter As mentioned in Lec 2, char can also perform arithmetic and comparison Example – Print the ASCII code of a character 5 #include

using namespace std;

void main(){

char c;

cout<<"Input a character: "; cin>>c;

int num = (int)c; //type casting

cout<<"The ASCII code is "<

using namespace std;

void main(){

char c1=’D’, c2=’e’, c3,c4;

c3=c1+’a’-‘A’; //convert to lowercase

c4=c2+’A’-‘a’; //convert to uppercase

cout<< "c3=" << c3 << ", c4=" << c4 << endl; //c3=d, c4=E } Reading a non-space character 7 char c1; cin >> c1;

When cin >> c1 is executed, the program will ask the
user for input (skipping all / characters)

Q: What if the user inputs more than 1 character ?

A: The extra characters are stored in the input buffer in
memory. When later >> are encountered, content from the
buffer is returned directly without waiting for user input.

Some facts about keyboard Input

8

c1 c2 c3 Input buffer
(user input ” cs2311″)

cin >> c1; ‘C’

cin >> c2; ‘C’ ‘S’

cin >> c3; ‘C’ ‘S’ ‘2’

char c1,c2,c3;

cin >> c1; //enter the string “CS2311”, c1 get ‘C’

cin >> c2; //c2 get the character ‘S’ from buffer

cin >> c3; //c3 get the character ‘2’ from buffer

Example

9

! Write a program which reads a character from the user and
output the character type.

! The program should distinguish between the following types of
characters
! An upper case character (‘A’-‘Z’)
! A lower case character (‘a’-‘z’)
! A digit (‘0’-‘9’)
! Special character (e.g. ‘#’, ‘$’, etc)

Exercise – Fill in the missing parts

10

#include

using namespace std;

void main(){

char c;

cin >> c;

if ( )

cout << "An upper case character\n"; else if ( ) cout << "A lower case character\n"; else if ( ) cout << "A digit\n"; else cout << "Special character\n"; } Answer 11 #include

using namespace std;

void main(){

char c;

cin >> c;

if (c>=’A’ && c<='Z') cout << "An upper case character\n"; else if (c>=’a’ && c<='z') cout << "A lower case character\n"; else if (c>=’0′ && c<='9') cout << "A digit\n"; else cout << "Special character\n"; } IMPORTANT: Note the difference between '0' and 0 Read any character with cin.get 12 ! cin.get(): member function of cin to read in one character from input ! Unlike cin>> , cin.get() WON’T skip over white spaces
(i.e. you can use it to read and )

! Syntax:
char c;

cin.get(c);

Read any character with cin.get

13

#include

using namespace std;

void main(){

char c;

do {

cin.get(c);

cout << c; }while (c!='\n'); } String -- as character array 14 cstring vs string object 15 ! In C++, there are two types of strings: ! As an array of char (the same mechanism as the C language), also known as the so-called cstring ! std::string class defined in C++ library
(not covered in this course)

String : cstring

16

! A cstring is a char array, which is terminated by the end-of-string
mark (also called null character) ‘\0’ (ASCII code:0).

! In other words, whatever enclosed by double quotation marks “..”
will have ‘\0’ automatically added to the end

! Because you need ‘\0’, so a character array of size n may stores
only strings with a maximum length of n-1

! Consider the definition

char str[20]=”Hello World”;

H e l l o W o r l d \0

This character array may store a string with maximum length of 19

Rule of Safety

17

! Declare a string with at least one character more than
needed

! E.g.
! char X[4]=”ABC”; //Correct
! char Y[3]=”ABC”; //Wrong, 3 is not enough!

char Y[3]=”ABC”; is actually IDENTICAL to..
char Y[3] = { ‘A’,’B’,’C’,’\0′ };

Obviously a [3] array cannot store 4 characters!

Double quotation mark for string

Single quotation mark for character

cstring: Declaration and Initialization

18

! String variable can be declared in one of the two ways:
! Without initialization

! char identifier[required size+1] , for example:
! char name[12]; // name with 11 characters
! char Address[50]; // address with 49 characters

! With initialization
! char identifier=string constant , for example:

! char name[5]=”John”; //name with 5 characters
! char name[]=”John”; //also ok
! char name[5]={‘J’,’o’,’h’,’n’,’\0′}; //also ok

! However, you cannot initialize a string after declaration
! char name[10];
! name=”john”; // wrong!

Compilation error : ‘=’ : cannot convert from
‘const char [5]’ to ‘char [10]’

cstring : Reading and Printing

19

The array word can store 20 characters but we can only store up to 19
“useful” characters (need to reserved 1 char for ‘\0’)

Note: cin would not check the size of array, hence inputting long string
(>19 chars) can result in runtime error!

#include

using namespace std;

void main(){

char word[20];

//read a string

cin >> word;

cout << word; //print a string } Reading a line of characters 20 ! cin >> str will stop when white space characters
(, , or ) are encountered

! Suppose “hello world” is inputted

char s[20];

cin >> s; //read ONLY “hello”

cin >> s; //read “world”

! Therefore, cin >> could not be used directly if the string
contains spaces

Read one line with cin.getline

21

! Member function of cin to read in a line of text
(including spaces) up to the character
(or until the specified number of characters are read)

! Two arguments:
! char array to receive the input
! size of the char array

#include

using namespace std;

void main(){

char s[20];

cin.getline(s,20);

cout << "\"" << s << "\"" << end; } Suppose "hello world" is inputted This time you get the full string but not just "hello" The Null Character '\0' 22 ! The null character '\0', is used to mark the end of a cstring ! '\0' is a single character (although written in two symbols) ! ASCII code of the null character is 0 Why we need '\0'? 23 ! cstring is stored in main memory continuously ! When the cstring is passed to functions (e.g. output with cout), only the start address is passed. (because the string is array). ! cout actually have NO IDEA how long the string is! ! cout simply keeps printing until '\0' is encountered. What if there's no '\0'? 24 #include

using namespace std;

void main(){

int a=98765432;

char s[]=”Hello world”;

s[11]=’ ‘; //deliberately overwrite the ‘\0’

cout << s <
using namespace std;
void main(){

char s[]=”A string! A long long long long string!”;

s[9]=’\0′; //cut at position 9
//although characters 10…end are not changed,
//but they are not printed as they are after ‘\0’

cout << s <
using namespace std;

int strlength(char s[]){
int i=0;
while (s[i]!=’\0′)

i++;
return i;

}
void main(){
char s[20]=”Hello world”;
cout << strlength(s); } Copy cstrings without using library 30 ! Suppose there are two strings, str1 and str2 ! str1 is initialized to "Hello world" ! Copy str1 to str2 ! We CANNOT use the following expression to copy array elements str2=str1; ! Similarly, we CANNOT use the following expression to compare strings if (str1==str2) ...... Copy cstrings without using library 31 ! Use a loop to read characters one by one from str1 until a null character ('\0') is read ! Copy the character to the corresponding position of str2 ! IMPORTANT: Remember to put a null character at the end of str2 The program 32 #include

using namespace std;

void main(){

char str1[20]=”Hello world”;

char str2[20];

int i;

/*beware of the boundary condition!*/

for (i=0; i<19 && str1[i]!='\0'; i++) { str2[i]=str1[i]; } str2[i]='\0'; //IMPORTANT cout << str2; } Exercise 33 ! Write a program to let the user input a line of string ! The program should reverse the case of the input characters and print the result ! Lowercase characters are changed to uppercase. ! Uppercase characters are changed to lower case ! Example input/output: Hello World hELLO wORLD Program – fill in the missing parts 34 #include

using namespace std;

void main(){

char s[20];

int i;

cin.getline(s);

for (i=0; s[i]!=’\0′; i++){

if ( ) //uppercase letter

cout << ; //convert to lowercase else if (s[i]>=’a’ && s[i]<='z') //lowercase letter cout << ; //convert to uppercase else //other characters cout << ; } } Answer 35 #include

using namespace std;

void main(){

char s[20];

int i;

cin.getline(s);

for (i=0; s[i]!=’\0′; i++){

if (s[i]>=’A’ && s[i]<='Z') //uppercase letter cout << s[i]+'a'-'A'; //convert to lowercase else if (s[i]>=’a’ && s[i]<='z') //lowercase letter cout << s[i]+'A'-'a'; //convert to uppercase else //other characters cout << s[i] ; } } The library

36

! Instead of writing loops on your own, you may
actually use the cstring library for:

! String copy (strcpy)
! String compare (strcmp)
! Find the length of string (strlen)
! Merging strings (strcat)
! Find a character from string (strchar)
! and more…

Some string functions in library

37

Function Description Remarks

strcpy (dest,src) Copy the content of string src to
the string dest

No error check on
whether the size of dest
is enough for holding src

strcat (dest,src) Append the content of string src
onto the end of string dest

No error check on
whether the size of dest
is enough for holding src

strcmp(s1,s2) Lexicographically compare two
strings, s1 and s2, character by
character.

0: s1 and s2 are identical
<0: s1 is less than s2 >0: s1 is greater than s1

strlen(string) Returns the number of
characters (exclude the null
character) in the string

Example

38

! Write a program to print a word backward.
! Example:

! Input:
! hello

! Output:
! olleh

The program – fill in the missing parts

39

#include

#include

using namespace std;

void main(){

char ____; //define an array input with size 20

int n; //length of str

int i;

cin >>____;

n=______; //compute string length

for (i=____; i >= 0 ;i–)

cout <<____ ; } The program 40 #include

#include

using namespace std;

void main(){

char input[50]; //define an array input with size 50

int n; //length of str

int i;

cin >> input;

n=strlen(input); //compute string length

for (i=n-1; i>=0; i–)

cout << input[i]; } cin.ignore (count, delimiter ) 41 ! Function to skip number of characters from the keyboard buffer (or until the delimiter is encountered) ! count: maximum number of characters to discard. ! delimiter: a character which signals the end of the ignore/discard operation. (Note: the “delimiter” is also removed) ! Example: ! cin.ignore(1000,'\n'); /* skip at most 1000 characters or until '\n' is found, */ ! cin.ignore(1000,'c'); /* skip at most 1000 characters or until 'c' is found, */ Example 42 #include

using namespace std;

void main(){

char name[20];

char address[20];

cin >> name;

cin.ignore(1000,’\n’);

cin >> address;

cout << name <<':'<

> of char skips . You may use cin.get(…) instead
! CString is an array of character terminated by ‘\0‘

(i.e. char Name[20] can store only 19 characters for the name)
! Access character from string is similar to accessing individual

element of an array
! String cannot be copied (=) and compared (==) directly
! Default cin>> of string stops when is encountered. You may

use cin.readline (…) to read the whole line (until )
! String copy, comparison, concatenate can be done by functions

provided by library

For reference: cin Error states
! From time to time, user’s input could be deviated from

the expectation
! e.g. cin>>integer but user input string
! e.g. cin.getline and user typed more than the array size

! For cases like that, cin.fail() will report true
! The “error” status persists and may hinder later cin

operations
! Solution:

! Call cin.clear() to cancel all “error” status
! Possibly need to call cin.ignore() to remove incorrect

input from the buffer

For reference: cin.fail() and cin.clear()

#include

using namespace std;

void main(){

int x;

while(1) {

cin>>x;

if (cin.fail()) {

cout<<"Error, input is not integer!\n"; cin.clear(); cin.ignore(1000,'\n'); //remove all illegal chars until ‘\n’ } else { cout<<"OK, input is integer "<