留学生考试辅导 CS2310 Computer Programming

Computer Science, City University of
Semester B 2021-22
CS2310 Computer Programming

Copyright By PowCoder代写 加微信 powcoder

LT8: Characters and Strings

Characters
Declaration and Initialization
Input and Output (cin,cout)
Declaration and Initialization
Copy and compare
Input and output

Character data type
Written between single quotes. Examples
‘A’, ‘b’, ‘*’
In C++ language, a char type is represented by an integer
Therefore, a character can also be treated as an integer

ASCII Table
cout << (int) ‘7’; cout << (char) 97; char features 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 ch is a lower-case letter: if ('a' <= ch && ch <= 'z') ... if (97 <= ch && ch <= 122) ... If the variable ch is a lowercase letter, then the expression ch – ‘a’ + 'A' /*same as ch -97 + 65*/ has the value of the corresponding uppercase letter #include
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 character char c1,c2; cin >> c1;
When cin >> c1 is reached, the program will ask the user for input.

Suppose the character ‘A’ is input, c1 will evaluate to 65 (which is the ASCII code of ‘A’).
As a result, 65 will be assigned to the character c1. Therefore, c1 holds the character ‘A’

Some facts about keyboard Input
Suppose >> is called to read a character.

What if the user input more than 1 characters in a single line?

Answer: The extra character will be stored in a buffer (certain memory location). The character will be retrieved later when >> is called to read more characters

Some facts about keyboard Input
c1 c2 c3 Input buffer

(user input “ cs2310”)

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

char c1,c2,c3;
cin >> c1; //enter the string “CS2310”
cin >> c2; //get the character ‘S’ from buffer
cin >> c3; //get the character ‘2’ from buffer

Printing a character
char c1=’A’,c2=’B’;
cout << c1; cout.put(c1); 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.) #include
using namespace std;
void main(){
if ( )//’A’-‘Z’
cout << "An upper case character\n"; else if ( )//‘a'-‘z' cout << "A lower case character\n"; else if ( )//‘0'-‘9' cout << "A digit\n"; cout << "Special character\n"; #include
using namespace std;
void main(){
if (‘A’ <=c && c<='Z') //'A'-'Z' cout << "An upper case character\n"; else if ('a' <= c && c<='z') //‘a'-‘z' cout << "A lower case character\n"; else if ('0' <= c && c<='9') //‘0'-‘9' cout << "A digit\n"; cout << "Special character\n"; cstring vs string object In C++, there are two types of strings cstring: inherited from the C language string: class defined in library

String : cstring
A cstring is a char array terminated by’\0′ (which is named null character) representing the end-of-string sentinel.
A character of array of size n may store a string with maximum length of n-1
Consider the definition

char str[20]=”Hello World”;

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

Rule of Safety
Declare a string with one more character than needed
char studentID[8+1]; //51234567
char HKID[10+1]; //a123456(7)

cstring: Declaration and Initialization
String variable can be declared in one of two ways
Without initialization
char identifier[required size+1]
char name[12]; // name with 11 characters
char Address[50]; // Address with 49 characters
With initialization
char identifier[]=string constant
char name[]=“John”; //name with 5 characters
char choice[]=“a,b,c,d,e”; //choice with 10 characters
However, you cannot initialize a string after declaration
char name[10];
name=“john”;

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

char grade;

cin>>mark;
if(mark>80)
grade=’A’; //grade=”A”;
else if(mark>60)
grade=’B’;
else if(mark>50)
grade=’C’;
grade=’F’;

cout<
using namespace std;
void main(){
char word[20];
cin >> word; //read a string

cout << word; //print a string Reading a line of characters cin >> str will terminate when whitespace characters (space, tab, linefeed, carriage-return, formfeed, vertical-tab and newline characters) is encountered

Suppose “hello world” is input
char s1[20],s2[10];
cin >> s1; //user input “hello world”
cin >> s2; //does not require user input
cout << s1; //output "hello" cout << s2; // output "world" How to read a line of characters (before ‘\n’ is encountered)? get(): member function of cin to read in one character from input cin.get(c); 1. cin.get + while loop #include
using namespace std;

void main(){
cin.get(c);
cout << c; }while (c!='\n');// before ‘\n’ is encountered 2. cin.getline Predefined member function of cin to read a line of text (including space) Two arguments: cstring variable to receive the input size of the cstring #include
using namespace std;
void main(){
char s[20];
while (1){
cin.getline(s,20);
cout << “\”” << s << “\”” << endl; cin.getline Input is longer than the string variable? End of the source characters is reached? Error occurred? Internal state flags (eofbit,failbit,badbit) of cin object will be set To reset those flags, call method clear() of cin. E.g. cin.clear(); #include
using namespace std;
void main(){
char s[5];
while (1){
cin.getline(s,5);

cout << “\”” << s << “\”” << endl; #include
using namespace std;
void main(){
char s[5];
while (1){
cin.getline(s,5);
cin.clear();
cout << “\”” << s << “\”” << endl; The Null Character ‘\0’ The null character,’\0’, is used to mark the end of a cstring ‘\0’ is a single character (although written in two symbols => escape sequence)
It is used to distinguish a cstring variable from an ordinary array of characters (cstring variable must contain the null character)

Why need ‘\0’?
cstring is stored in main memory continuously
Only the starting address of the cstring is stored in cstring variable
char s1[]=“Hello World”; // s1=20
char s2[]=“cs2310”; // s2=32
‘\0’ indicates the end of cstring

0 1 2 3 4 5 6 7 8 9
0 r o g r a m m i n a
1 O – m a 4 1 . ; t a
2 H e l l o w o r l
3 d \0 c s 2 3 1 0 \0 &
4 1 * ~ ^ b / a v e

Why need ‘\0’?
When a cstring variable is passed to a output function, i.e. cout, the function will print all the memory content until ‘\0’ is encountered
0 1 2 3 4 5 6 7 8 9
0 r o g r a m m i n a
1 O – m a 4 1 . ; t a
2 H e l l o w o r l
3 d \0 c s 2 3 1 0 \0 &
4 1 * ~ ^ b / a v e

Why need ‘\0’?
#include
using namespace std;
void main(){
char s1[]=”cs2310″;
char s2[]=”Hello world”;

s2[11]=’ ‘;//change ‘\0’ to a space character ‘ ‘;
cout << s2; cout << endl; Passing strings to functions Write a function to count the frequency of a character (e.g., ‘a’) in a string count: given a character and a string as input, return the frequency of the character in the string main function: call count function Function : count int count(char s[100], char c){ int frequency=0; while (s[i]!='\0') if (s[i]==c) frequency++; return frequency; The size 100 is optional Function : count int count(char s[100], char c){ int frequency=0; while (s[i]!='\0') if (s[i]==c) frequency++; return frequency; The size 100 is optional The main function void main(){ char str[50]=”CityU is a very good university"; int freq = count(str, 'a'); cout << " freq = “ << freq << “ \n"); int count(char s[100], char c) Common cstring functions in
Function Description Remarks
strcpy (dest, src) Copy the content of string src to the string dest No error check on 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 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 is identical
>0: s1 is greater than s2
<0: s1 is less than s1 strlen(str) Returns the number of characters (exclude the null character) contain in string str Note: you may need to use strcpy_s and strcat_s instead of strcpy and strcat if you are using the latest visual studio. strcpy (dest, src), strcat (dest, src) #include
using namespace std;

int main() {
char src[] = “This is CS2310”;
char dest[40]; 
strcpy(dest, src);
cout << dest << endl; strcat(dest, " Lecture09."); cout << dest << endl; Try to implement: copy Suppose there are two strings, str1 and str2 str1 is initialized to "Hello world" Copy str1 to str2 We should NOT use the following expression to copy array elements str2=str1; Similarly, we should NOT use the following expression to compare strings if (str1==str2) ...... 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 Put a null character at the end of str2 The program #include
using namespace std;
void main(){
char str1[20]=”Hello world”;
char str2[16];

/*beware of the boundary condition!*/
for (i=0; i<15 && str1[i]!='\0'; i++) { str2[i]=str1[i]; str2[i]='\0'; cout << str2; Try to implement: append content #include
using namespace std;

void main(){
char s1[20]=”Welcome to “;
char s2[20]=”CS2310”;
long s1_length = strlen(s1);
long s2_length = strlen(s2);
char s[100];
long i = 0;
for (; i
using namespace std;

int main() {
char str[50];
strcpy(str, “This is CS2310”);
len = strlen(str);
cout << “The length of str is ” << len << endl; Try to implement: string length #include
using namespace std;

int length_of_string (char s[]){
int length = 0;
while (s[length]!=‘\0’)
return length;
void main(){
char s[20]=”Hello world”;
cout << length_of_string(s); strcmp(s1, s2) #include
using namespace std;

int main() {
    char str1[15];
    char str2[15];
    strcpy(str1, “abcdef”);
    strcpy(str2, “ABCDEF”);
    ret = strcmp(str1, str2);
    if(ret < 0)         cout << "str1 is smaller than str2" << endl;     else if(ret > 0)
        cout << "str2 is smaller than str1" << endl;         cout << "str1 is equal with str2" << endl; Try to implement: Compare two strings with the same length #include
using namespace std;

int main(){
    char s1[15] = “abcdef”;
    char s2[15] = “abcdEF”;
    long size = strlen(s1);
    for (int i = 0; i < size; i++) {         if (s1[i] < s2[i]) {             cout << "str1 is smaller than str2" << endl;             return -1;         } else if (s1[i] > s2[i]) {
            cout << "str2 is smaller than str1" << endl;     cout << "str1 is equal with str2" << endl; Write a program to print a word backward. The program #include
using namespace std;
void main(){
char ____; //define an array input with size 20
int n; //length of str

cin >>____;
n=______; //compute string length
for (i=____; i > 0 ;i–)
cout <<____ ; Write a program to let the user to input a line of string from the user 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 lowercase Example input/output: Hello World hELLO wORLD #include
using namespace std;
void main(){
char s[20];
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 << ; #include
using namespace std;
void main(){
char s[20];
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] ; /docProps/thumbnail.jpeg 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com