Documente Academic
Documente Profesional
Documente Cultură
http://www.comp.nus.edu.sg/~cs1010/
References:
Lesson 1.4.1 Characters and Symbols
Chapter 7: Strings and Pointers
Week9 - 2
ASCII
Demo #1: Using characters
Demo #2: Character I/O
Demo #3: Character functions
Common Error
Exercise #1: Summing Digit Characters
4. Strings
4.1
4.2
4.3
4.4
Basics
String I/O (with Demo #4)
Quick Quiz
Demo #5: Remove Vowels
Week9 - 3
5.
6.
7.
8.
9.
10.
11.
Pointer to String
Array of Strings
Array of Pointers to Strings
Exercise #2: Hangman Game version 2
String functions (with Demo #7)
Exercise #3: Arrow Program
Command-line arguments
Week9 - 4
Examples:
Valid path: E, E, S, N, E, E, S
Invalid path: S, S, W
Invalid path: S, S, S, E
0
1
2
3
4
Write a function
5
int isValid (int maze[][6], char path[])
that takes in a 6 6 maze and a path with at most 10 characters.
It returns 1 if path is valid in maze, or returns 0 otherwise.
This is a take-home exercise.
An incomplete program Week8_IsValid.c is given. It handles string
input which is not covered yet.
Week9 - 5
Week9 - 6
2. Motivation
Week9 - 7
3. Characters
Week9 - 8
70
For
Forexample,
example,
character
character'O'
'O'isis
79
79(row
(rowvalue
value
70
+
col
value
70 + col value99
==79).
79).
Week9 - 9
Week9_CharacterDemo1.c
// Week9_CharacterDemo1.c
#include <stdio.h>
int main(void) {
grade = A
newgrade = C
newgrade = 67
value = 65
value = A
Relationship between
character and integer.
Week9 - 10
=
=
=
=
=
p
q
r
s
t
Week9 - 11
//
// Week9_CharacterDemo2.c
Week9_CharacterDemo2.c
#include
#include <stdio.h>
<stdio.h>
int
int main(void)
main(void) {{
char
char ch;
ch;
Week9_CharacterDemo2.c
Read a character
from stdin.
printf("Enter
printf("Enter aa character:
character: ");
");
ch
ch == getchar();
getchar();
Enter a character: W
Character entered is W
printf(Character
printf(Character entered
entered is
is ");
");
putchar(ch);
putchar(ch);
putchar('\n');
putchar('\n');
}}
return
return 0;
0;
Print a character
to stdout.
Week9 - 12
Week9_CharacterDemo3.c
// Week8_CharacterDemo3.c
#include <stdio.h>
#include <ctype.h>
int main(void) {
char ch;
printf("'%c'
printf("'%c'
printf("'%c'
printf("'%c'
is
is
is
is
}
CS1010 (AY2012/3 Semester 1)
Week9 - 13
// Week8_CharacterDemo3.c
#include <stdio.h>
#include <ctype.h>
int main(void) {
char ch;
Week9_CharacterDemo3.c
Week9 - 14
char
char A,
A, B,
B, C,
C, D,
D, F;
F;
if
if (marks
(marks >=
>= 80)
80)
return
return A;
A;
else
else if
if (marks
(marks >=
>= 70)
70)
return
return B;
B;
else
else if
if (marks
(marks >=
>= 60)
60)
return
return C;
C;
.. .. ..
if
if (marks
(marks >=
>= 80)
80)
return
return 'A';
'A';
else
else if
if (marks
(marks >=
>= 70)
70)
return
return 'B';
'B';
else
else if
if (marks
(marks >=
>= 60)
60)
return
return 'C';
'C';
.. .. ..
char
char grade;
grade;
if
if (marks
(marks >=
>= 80)
80)
grade
grade == 'A';
'A';
else
else if
if (marks
(marks >=
>= 70)
70)
grade
grade == 'B';
'B';
else
else if
if (marks
(marks >=
>= 60)
60)
grade
grade == 'C';
'C';
.. .. ..
return
return grade;
grade;
Week9 - 15
4. Strings
c s 1 0 1 0 \0
Week9 - 17
Two ways:
char fruit_name[] = "apple";
char fruit_name[] = {'a','p','p','l','e','\0'};
Week9 - 18
Week9 - 19
fgets()
On interactive input, fgets() also reads in the newline
character
User input: eat
e a t \n \0 ? ?
Week9 - 20
Week9_StringIO1.c
Test out the programs with this input:
My book
int
int main(void)
main(void) {{
char
char str[LENGTH];
str[LENGTH];
}}
printf("Enter
printf("Enter string
string
scanf("%s",
str);
scanf("%s", str);
printf("str
printf("str == %s\n",
%s\n",
return
return 0;
0;
#include
#include <stdio.h>
<stdio.h>
#define
#define LENGTH
LENGTH 10
10
(at
(at most
most %d
%d characters):
characters): ",
", LENGTH-1);
LENGTH-1);
str);
str);
Week9_StringIO2.c
int
int main(void)
main(void) {{
char
char str[LENGTH];
str[LENGTH];
}}
printf("Enter
printf("Enter string
string (at
(at most
most %d
%d characters):
characters): ",
", LENGTH-1);
LENGTH-1);
fgets(str,
fgets(str, LENGTH,
LENGTH, stdin);
stdin);
printf("str
printf("str == ");
");
puts(str);
puts(str);
return
return 0;
0;
Week9 - 21
No
No
Week9 - 22
A sample run:
Enter a string: How HAVE you been?
New string: Hw HV y bn?
Week9 - 23
#include
#include <stdio.h>
<stdio.h>
#include
#include <string.h>
<string.h>
#include
#include <ctype.h>
<ctype.h>
int
int main(void)
main(void) {{
int
int i,
i, len,
len, count
count == 0;
0;
char
char str[101],
str[101], newstr[101];
newstr[101];
Week9_RemoveVowels.c
printf("Enter
printf("Enter aa string
string (at
(at most
most 100
100 characters):
characters): ");
");
fgets(str,
fgets(str, 101,
101, stdin);
stdin); //what
//what happens
happens if
if you
you use
use scanf()
scanf() here?
here?
len
len == strlen(str);
strlen(str); //
// strlen()
strlen() returns
returns number
number of
of char
char in
in string
string
if
if (str[len
(str[len 1]
1] ==
== '\n')
'\n')
str[len
str[len 1]
1] == '\0';
'\0';
len
len == strlen(str);
strlen(str); //
// check
check length
length again
again
}}
for
for (i=0;
(i=0; i<len;
i<len; i++)
i++) {{
switch
switch (toupper(str[i]))
(toupper(str[i])) {{
case
case 'A':
'A': case
case 'E':
'E':
case
case 'I':
'I': case
case 'O':
'O': case
case 'U':
'U': break;
break;
default:
default: newstr[count++]
newstr[count++] == str[i];
str[i];
}}
}}
newstr[count]
newstr[count] == '\0';
'\0';
printf("New
printf("New string:
string: %s\n",
%s\n", newstr);
newstr);
return
return 0;
0;
Week9 - 24
#include <stdio.h>
#include <string.h>
int main(void) {
char str[10];
str[0]
str[1]
str[2]
str[3]
str[4]
=
=
=
=
=
'a';
'p';
'p';
'l';
'e';
Week9_without_null_char.c
One possible output:
Length = 8
str = apple<
Compare the output if you add:
str[5] = '\0';
or, you have:
char str[10] = "apple";
Week9 - 25
Week9 - 26
Number of lives: 5
Guess a letter in the
h
Number of lives: 4
Guess a letter in the
p
Number of lives: 4
Guess a letter in the
b
Number of lives: 3
Guess a letter in the
m
Number of lives: 2
Guess a letter in the
x
Number of lives: 1
Guess a letter in the
i
Sorry, youre hanged!
"apple".
CS1010 (AY2012/3 Semester 1)
word _ _ _ _ _
word _ _ _ _ _
word _ p p _ _
word _ p p _ _
word _ p p _ _
word _ p p _ _
Number of lives: 5
Guess a letter in the word _
p
Number of lives: 5
Guess a letter in the word _
e
Number of lives: 5
Guess a letter in the word _
o
Number of lives: 4
Guess a letter in the word _
a
Number of lives: 4
Guess a letter in the word a
l
Congratulations! The word is
The word is
Week9 - 27
_ _ _ _
p p _ _
p p _ e
p p _ e
p p _ e
"apple".
Week9_Hangman_v1.c
int
int has_letter(char
has_letter(char [],
[], char);
char);
int
int main(void)
main(void) {{
char
char input;
input;
char
char word[]
word[] == "apple";
"apple";
char
char temp[]
temp[] == "_____";
"_____";
int
int i,
i, count
count == 0;
0;
int
int num_lives
num_lives == 5;
5;
int
int length
length == strlen(word);
strlen(word);
Week9 - 28
if
if (has_letter(word,
(has_letter(word, input))
input)) {{
for
for (i=0;
(i=0; i<length;
i<length; i++)
i++)
if
if ((input
((input ==
== word[i])
word[i]) &&
&& (temp[i]
(temp[i] ==
== '_'))
'_')) {{
temp[i]
temp[i] == input;
input;
count++;
count++;
}}
}}
else
else num_lives--;
num_lives--;
}} while
while ((num_lives
((num_lives !=
!= 0)
0) &&
&& (count
(count !=
!= length));
length));
}}
if
if (num_lives
(num_lives ==
== 0)
0)
printf("Sorry,
printf("Sorry, you're
you're hanged!
hanged! The
The word
word is
is \"%s\"\n",
\"%s\"\n", word);
word);
else
else
printf("Congratulations!
printf("Congratulations! The
The word
word is
is \"%s\"\n",
\"%s\"\n", word);
word);
return
return 0;
0;
Week9 - 29
return
return 0;
0;
//
// ch
ch does
does not
not occur
occur in
in word
word
Week9 - 30
printf("name
printf("name == %s\n",
%s\n", name);
name);
printf("namePtr
printf("namePtr == %s\n",
%s\n", namePtr);
namePtr);
printf("Address
printf("Address of
of 1st
1st array
array element
element for
for name
name == %p\n",
%p\n", name);
name);
printf("Address
printf("Address of
of 1st
1st array
array element
element for
for namePtr
namePtr == %p\n",namePtr);
%p\n",namePtr);
strcpy(name,
strcpy(name, "Lee
"Lee Hsu");
Hsu");
namePtr
namePtr == "Lee
"Lee Hsu";
Hsu";
}}
printf("name
printf("name == %s\n",
%s\n", name);
name);
printf("namePtr
printf("namePtr == %s\n",
%s\n", namePtr);
namePtr);
printf("Address
printf("Address of
of 1st
1st array
array element
element
printf("Address
printf("Address of
of 1st
1st array
array element
element
Week9_StringPointer.c
CS1010 (AY2012/3 Semester 1)
for
for name
name == %p\n",
%p\n", name);
name);
for
for namePtr
namePtr == %p\n",namePtr);
%p\n",namePtr);
Address of first array element for name
remains constant, string assigned to
namePtr changes on new assignment.
Week9 - 31
Week9 - 31
Comparison
char name[12] = "Chan Tan";
name[0]
C
namePtr
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
n \0 \0 \0 \0
n \0
Week9 - 32
[10]
[11]
6. Array of Strings
Declaration
char fruits[MAXNUM][STRSIZE];
// where MAXNUM is the maximum number of names
// and STRSIZE is the size of each name
Initialization
char fruits[][6] = {"apple", "mango", "pear"};
or
char fruits[3][6] = {"apple", "mango", "pear"};
Output
printf("fruits: %s %s\n", fruits[0], fruits[1]);
printf("character: %c\n", fruits[2][1]);
fruits: apple mango
character: e
Week9 - 33
Declaration
char *fruits[3];
Assignment
fruits[0] = "apple";
fruits[1] = "banana";
fruits[2] = "cherry";
pear
banana
cherry
Output
for (i=0; i<3; i++)
printf("%s\n", fruits[i]);
Week9 - 34
8. Ex #2 (take-home): Hangman
Game ver2
Week9 - 35
http://www.cs.cf.ac.uk/Dave/C/node19.html
strcmp(s1, s2)
strcpy(s1, s2)
strncpy(s1, s2, n)
Week9 - 37
\0
strstr(s1, s2)
Week9 - 38
#include
#include <stdio.h>
<stdio.h>
#include
#include <string.h>
<string.h>
#define
MAX_LEN
#define MAX_LEN 10
10
int
int main(void)
main(void) {{
char
char s1[MAX_LEN
s1[MAX_LEN ++ 1],
1], s2[MAX_LEN
s2[MAX_LEN ++ 1],
1], *p;
*p;
int
int len;
len;
printf("Enter
printf("Enter string
string (at
(at most
most %d
%d characters)
characters) for
for s1:
s1: ",
", MAX_LEN);
MAX_LEN);
fgets(s1,
MAX_LEN+1,
stdin);
fgets(s1, MAX_LEN+1, stdin);
len
len == strlen(s1);
strlen(s1);
if
if (s1[len
(s1[len 1]
1] ==
== '\n')
'\n') s1[len
s1[len 1]
1] == '\0';
'\0';
printf("Enter
printf("Enter string
string (at
(at most
most %d
%d characters)
characters) for
for s2:
s2: ",
", MAX_LEN);
MAX_LEN);
fgets(s2,
fgets(s2, MAX_LEN+1,
MAX_LEN+1, stdin);
stdin);
len
len == strlen(s2);
strlen(s2);
if
if (s2[len
(s2[len 1]
1] ==
== '\n')
'\n') s2[len
s2[len 1]
1] == '\0';
'\0';
printf("strcmp(s1,s2)
printf("strcmp(s1,s2) == %d\n",
%d\n", strcmp(s1,s2));
strcmp(s1,s2));
pp == strstr(s1,s2);
strstr(s1,s2);
if
(p
if (p !=
!= NULL)
NULL) printf("strstr(s1,s2)
printf("strstr(s1,s2) returns
returns %s\n",
%s\n", p);
p);
else
else printf("strstr(s1,s2)
printf("strstr(s1,s2) returns
returns NULL\n");
NULL\n");
}}
strcpy(s1,s2);
strcpy(s1,s2);
printf("After
printf("After strcpy(s1,s2),
strcpy(s1,s2), s1
s1 == %s\n",
%s\n", s1);
s1);
return
return 0;
0;
Week9 - 39
Week9 - 40
A sample run:
Enter
Enter names:
names:
Khoo
Khoo Siau
Siau Cheng
Cheng
Hsu
Hsu Wynne
Wynne
Lee
Lee Mong
Mong Li
Li
Aaron
Aaron Tan
Tan
Zhou
Zhou Lifeng
Lifeng
Zhao
Zhao Jin
Jin
(user
(user pressed
pressed ctrl-d
ctrl-d here)
here)
Name
Name selected:
selected:
Siau
Siau Khoo,
Khoo, would
would you
you please
please answer
answer the
the question?
question?
Week9 - 41
Week9 - 42
gcc Week9_CommandLineArgs.c
a.out water "ice cream" 34+7
This program was called with "a.out"
argv[1] = water
argv[2] = ice cream
argv[3] = 34+7
Week9 - 43
Characters
Strings
Week9 - 44
Announcements/Things-to-do
Lab #4 Deadline
Week9 - 45
End of File