C||C++

시스템프로그래밍 중간정리(lect 5)

Yongbaldae 2023. 5. 6. 01:13

- String definition

  A string is a character array ending with 0.

  Remember there is a hidden zero at the end of a string.

  Thus "hello" occupies 6 bytes not 5 bytes.

 

string functions: strlen, strcpy, strcmp, strtok

char *x = “hello”;              // store addr of “hello” in x

printf(“%d\n”, strlen(x));  .  // length of string. 5

char y[10];

strcpy(y, x);                     // store “hello” in y

y = x;                            // error.

if (strcmp(y, “hello”)==0)){  // strcmp returns 0 if same string

   .........

}

if (y==“hello”){         // this is wrong

   .........

}

 

Declaration, assignment, reading, writing, comparing

char y;          // y is a room for a character

y = ‘t’;          // we can store a character in y

scanf(“%c”, &y); // or we can read a character into y

printf(“%c”, y);  // print a character

if (y==’t’){      // check the value of y

   ......

}

 

char z[50];         // z is a 50-room space for a string

strcpy(z, “korea”);  // we have to use strcpy() to store a string in z

scanf(“%s”, z);      // or we can read a string into z

printf(“%s”, z);      // print a string

if (strcmp(z, “korea”)==0){             // check the value of z

   ........

}

 

string error

char x[20];          // x has 20 byte space.

strcpy(x, “hello”);  // ok. we store “hello” in x array.

x=“hello”;           // error. “hello” is an address. x is not a pointer.

char *y;             // y has 4 byte space for an address.

y=“hello”;          // ok. “hello” is an address. we store it in y.

strcpy(y, “hello”);  // error. y has no space for “hello”.

y=new char[20];   // y points to 20 byte space. 얘는 y에 크기20짜리 배열주소를 준다.

strcpy(y, “hello”);  // ok. we store “hello” in space pointed to by y

 

만약

char a[5];

for(i=0;i<5;i++){

   a[i]='q';

}

이처럼 끝에 0을 넣지 않으면 a는 string이 아닌것이 되고, 이는 printf("%s",a); 를 사용할 때 끝으로 인식하는 0을 찾을 수 없으므로 그 후에 존재하는 주소들의 캐릭터들을 계속해서 출력하게 된다.  

strtok

  char buf[]="ab c def"; 이렇게도 string을 넣을 수 있다

      //buf contains (a, b, space, c, space, d, e, f, 0)

   char *temp;

   temp=strtok(buf, " "); 

      // buf is now (a, b, 0, c, space, d, e, f, 0)

      // and temp has the address of buf[0].

   printf(“%s\n”, temp);    // “ab”

   temp=strtok(NULL, " ");

      // buf is now (a, b, 0, c, 0, d, e, f, 0)

      // temp has the address of buf[3]

    printf(“%s\n”, temp);   // “c”

    temp=strtok(NULL, " ");

      // buf is now (a, b, 0, c, 0, d, e, f, 0)

      // temp has the address of buf[5]

    printf(“%s\n”, temp); // “def

    temp=strtok(NULL, " ");  // no more tokens, so NULL will be returned in temp

자세히 보면 반복되는 부분이 있다. 이것을 수정하면....

   char buf[256];

   char *token;

   printf(“enter a sentence\n”);

   fgets(buf, 255, stdin);   // read a line (maximum size 255) 버프에 최대크기 255까지 담아놓는다.

   buf[strlen(buf)-1]=0;    // remove enter key

   token = strtok(buf, “ “); // get the first token

   for(;;){

      printf(“%s\n”, token);

      token = strtok(NULL, “ “); // get the next token

      if (token==NULL) break;

   }

 

Tip.

1. scanf 함수는 기본적으로 공백을 구분자로 사용하여 입력을 처리합니다

즉, sentence를 처리할 때는 scanf가 아닌 fgets를 사용하는 것이 더 적합합니다.

 

2. fgets는 문자열 끝에 줄 바꿈 문자('\n')를 포함합니다. 따라서 문자열 처리 시에 이를 고려해야 합니다. 즉, fgets함수를 사용할 때는 문자열 끝에 줄 바꿈 문자를 \0으로 대체하는 작업이 필요할 수 있습니다.

 

3. C 언어에서 문자를 비교할 때는 단일 따옴표(')를 사용해야 합니다. == 연산자를 사용하여 문자를 비교할 때는 '\n'과 같이 단일 따옴표를 사용하고, 문자열을 비교할 때는 "bye"와 같이 이중 따옴표를 사용해야 합니다.