c中字符串处理真的超级麻烦,字符串只是一个字符数组,操作起来除了角标就是指针,真的没有便捷的方式啊。!
1单词长度(4分)
题目内容:
你的程序要读入一行文本,其中以空格分隔为若干个单词,以‘.’结束。你要输出这行文本中每个单词的长度。这里的单词与语言无关,可以包括各种符号,比如“it’s”算一个单词,长度为4。注意,行中可能出现连续的空格。输入格式:
输入在一行中给出一行文本,以‘.’结束,结尾的句号不能计算在最后一个单词的长度内。输出格式:
在一行中输出这行文本对应的单词的长度,每个长度之间以空格隔开,行末没有最后的空格。输入样例:
It’s great to see you here.输出样例:
4 5 2 3 3 4
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
// printf("Hello, World!\n");
// char *s = (char*)malloc(sizeof(char) * 400);
// scanf("%[^\n]", s);
char *s = "It's great to see you here.";
// printf("%s\n", s);
// hello world , I am here;
char *dst = (char*)malloc(sizeof(char) * 20);
int i = 0;
int ci = 0;
while (1) {
int slen = (int) strlen(s);
if ('.' != s[slen - 1]) {
printf("%s\n", "必须是.号结尾的!");
break;
}
// printf("s =[%s]\n", s);
if (s + i == NULL || *(s + i) == '.') {
// printf("len=%d\n", i);
dst[ci] = (char) (i + ('1' - 1));
// printf("%s\n", ".......finish......");
break;
}
int space = 0;
if (' ' == *(s + i)) {
space = 1;
if (i == 0) {
// need drop
s += 1;
} else {
// need memo
// printf("len=%d\n", i);
s = s + i;
dst[ci] = (char) (i + '1' - 1);
dst[ci + 1] = ' ';
ci += 2;
// s += i + 1;
}
}
if (space) {
i = 0;
} else {
i++;
}
}
printf("%s\n", dst);
free(dst);
return 0;
}
console:
It's great to see you here.
4 5 2 3 3 4
Process finished with exit code 0