CS计算机代考程序代写 Lecture 12-2 Strings

Lecture 12-2 Strings

2
Objectives
At the end of this lecture, you should be able to
• Explain the difference between character and character pointer
• Explain how a string is represented in C
• Use library functions to manipulate chars and strings

Read & watch
• English textbook 5 or • No textbook? Go to
tutorialspoint.com – C Strings
• Video clip at C Programming Tutorials https://www.youtube.com/playlist?lis t=PL6gx4Cwl9DGAKIXv8Yr6nhGJ9 Vlcjyymq
– 45
3

4
Characters
• A character is represented by the char code (ASCII code)
• Data type: char
• Memory size: 1 byte
• It keeps only one character!
• Note: a char variable can be treated as an integer variable

Character library
• Alibraytotestcharactersandtoconvertbetween lower and upper case letters
• Readmoreatctype.h
• Page 249(eng) or page 199 (sv)
5

6
Strings
• A string is represented by an array of chars, terminated by ’\0’
• Example string declarations
char amessage[ ] = “now is the time”; char btext[ 100 ] = “this is a string”; char cstring [ 50];
• How do they work? – Memory view?
– String operations?

Character pointers
• Character pointer vs string
• char amessage[ ] = ” now is the time “; – An array is used to represent a string
• char *pmessage = ” now is the time “;
– a char pointer points to a char (could be starting char of a string)
7

Character pointer example
• strlen: return length of a string int strlen(char *s){ //version 1
int n;
for (n = 0; *s != ‘\0’, s++)
n++; return n;
}
• How it works?
8

Character pointer example
• strlen: return length of a string int strlen(char *s){ //version 2
char *p = s; while (*p != ‘\0’)
p++; return p – s;
}
• How it works?
9

10
Example strcpy.c
void strcpy( char *s, char *t); // s t
• Various versions
• How to copy string in C
char str1[ 100 ] = ”hello, world”; char str2[100];
char *ps;
• it is not allowed to do str2 = str1 in C
– You have to do char-by-char copy or strcpy() – Question
strcpy(ps, str1); // does this work? ps is not initialized!!

Study strycpy()
Subscript version
void strcpy( char *s, char *t){ int i;
Pointer versions
void strcpy1 ( char *s, char *t){ while ( (*s = *t) != ‘\0’ ) {
s ++; t ++; }
}
void strcpy2 ( char *s, char *t){
while ( (*s++ = *t++) != ‘\0’) ;
}
void strcpy3( char *s, char *t){
while ( *s++ = *t++) ;
}
i = 0;
while ( (s[i] = t[i]) != ‘\0’ )
i ++; }
11

String libarary
• With functions for string manipulations
• Read more about string.h
• Page 249-250
12

Poll questions https://sv.surveymonkey.com/r/SWDHJR6
13