C語言一題問

2009-04-14 6:05 am
strtok 的使用
•使用gets讓使用者輸入一字串
•使用strtok切割使用者輸入字串為個別token
•將這些token用printf分列輸出。輸出時所有token靠右對齊長度最長的token

EX:
輸入:This is a test string.
輸出:
-This
----is
-----a
--test
string.
(減號是空白鍵的意思)

回答 (1)

2009-04-14 7:44 am
✔ 最佳答案
#include <stdio.h>
#include <string.h>

int main()
{
char str[256];
char tmp[256];
char *ptr;
char ch;
int i,j;

printf("Please enter a sentence.\n");
if (gets(str) == NULL) {
printf("error in reading from gets\n");
exit(1);
}

strcpy(tmp,str);
ptr = strtok(tmp," ");
i = 0;

while (ptr != NULL) {
if ( strlen(ptr) > i ) {
i = strlen(ptr);
}
ptr = strtok(NULL," ");
}

strcpy(tmp,str);
ptr = strtok(tmp," ");

while (ptr != NULL) {
j = strlen(ptr);
while (j < i) {
printf(" ");
j++;
}
printf("%s\n",ptr);
ptr = strtok(NULL," ");
}

}

// Not optimal but works.



收錄日期: 2021-04-29 22:18:15
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090413000016KK10646

檢視 Wayback Machine 備份