2
Preview
String
– String: 일련의 characters들로 구성
– C에서 String 은 char의 one-dimensional array로 표현
– String은 반드시 맨 마지막에 null 문자 ‘0’가 있어야 함
– C에서는 String process를 위한 여러 가지 Built-in Functions을
제공
3.
3
The End-of-String Sentinel‘0’
String 정의 방법
– 3글자를 저장했지만, 실제로는 4bytes가 필요하다.
char word[100];
word[0] = ‘a’;
word[1] = ‘b’;
word[2] = ‘c’;
word[3] = ‘0’; /* string의 끝표시를 위해 null char 삽입*/
4.
4
Initialization of Strings
Use array name
– String의 process를 위해 char array를 사용
[Ex] char word[4] = “abc”;
[Ex] char word[4] = {‘a’, ‘b’, ‘c’, ‘0’ };
[Ex] char word[] = {‘a’, ‘b’, ‘c’, ‘0’ };
[Ex] char word[] = “abc”; compiler에 의해 자동으로
4 char를 위한 array생성
5.
5
Displaying String andcharacters
printf()
– String출력을 위해서는 %s 를 사용
– 출력이 성공적이면 출력된 글자 수 반환, 그렇지
않으면 -1 반환
[Ex] int nchars;
char p[ ] = “Hello! the world”;
nchars = printf(“%s”, p);
printf(“nnum of chars=%dn”, nchars);
Hello! the world
num of chars = 16
6.
6
Displaying String andcharacters
puts()
– printf()보다 fast, simple
– String의 출력 후, next line으로 자동 이동
int puts(char *str); /*function prototype */
return
- no. of chars written if successful
- EOF(-1) if not
[Ex] char p[ ] = “Hi !!”;
puts(p);
puts(“Hello!!”); Hi !!
Hello!!
7.
7
Reading Strings fromthe KB
scanf()
– %s : next white space char올 때까지 read
– %ns : n개의 chars 를 read, 단 그 전에 white space가 오게
되면 white space까지를 read
int scanf(char *format, argument_list);
return
- no. of successfully matched and input items
- 0 if not
8.
8
Reading Strings fromthe KB
[Ex] char name[80];
scanf(“%s”, name); /* name <- SKKU */
SKKU Univ. 입력 시
[Ex] char name[80];
scanf(“%3s”, name); /* name <= C-P */
scanf(“%8s”, name); /* name <= rogram */
C-Program is 입력 시
White space올 때까지 read
3개의 char를 read
9.
9
Reading Strings fromthe KB
gets()
– KB로부터 ‘n’까지, 즉 line단위로 read
– ‘n’은 자동 ‘0’로 convert되어 string끝에 저장된다.
char* gets(char *format);
return
- the address of the string
- NULL if EOF (end-of-file)
scanf()를 통하여 String을 입력 받는 경우:
• white space의 skip으로 white space의 read 불가능.
• Line 단위로 string을 입력 받을 수 없다.
10.
10
Reading Strings fromthe KB
[Ex] char data[81], *P;
while( gets(data) != NULL) {
printf(“%sn”, data);
}
or while(gets(data) != 0)
^D를 입력할 때까지 line단위로
read하여 그대로 화면에 출력
하는 program
<blank line> 입력 시 혹은
<[ctrl] + D> 입력 시 종료
11.
11
Reading Strings fromthe KB
char a[5], b[4]=“1234”;
scanf(“%s”, a);
printf( “%s %sn”, a, b ) ;
Array크기보다 더 많은 문자를 입력한 경우
– “abcde”를 입력하면 출력 값은?