我希望用户输入文本,程序会找到大于5个字母的所有单词并打印出来。
scanf("%[^\n]s", ar);
l = strlen(ar);
for (n = 0; n < l; n++) {
while (ar[n] != ' ') {
if (ar[n] != ' ') {
???
}
break;
if (ar[n] == ' ') {
???
}
}
}
答案 0 :(得分:1)
相对简单而强大的方法是:
答案 1 :(得分:1)
有很多方法可以完成这项任务。您可以使用开始和结束指针,然后向下遍历每个字符串,在每个分隔符处放置空终止字符,并按原样读取每个单词,或者您可以调用strtok
并让它解析每一行。 注意: strtok
会更改/销毁原始字符串,因此您需要复制strtok
。 (如果动态分配了副本,请确保保留起始地址,以便以后可以释放它。)
使用strtok
解析单词的方便方法是在for
循环中,它优雅地将第一个调用作为初始条件处理,并将所有后续调用作为增量处理。虽然循环很好,但for
在这里很难被击败。
解析单词后,只需获取长度并将其与用户输入的值进行比较即可。如果您有任何问题,请查看以下内容并告诉我:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
char *ar[] = { "The cat jumped over the lazy dog.",
"The quick brown fox jumps over a lazy dog.",
"The little boy exclaimed to see such a sight,",
"and the dish ran away with the spoon.", NULL };
size_t idx = 0;
size_t lim = 0;
printf ("\n The strings in the array:\n\n");
while (ar[idx])
printf (" %s\n", ar[idx++]);
printf ("\n enter minumum length for string match : ");
scanf ("%zu", &lim);
idx = 0;
while (ar[idx])
{
char *s = strdup (ar[idx]);
char *p = s;
size_t len = 0;
printf ("\n string: %s\n\n", ar[idx]);
for (p = strtok (s, " "); p != NULL; p = strtok (NULL, " "))
if ((len = strlen (p)) >= lim)
printf (" %-10s : %zu\n", p, len);
printf ("\n");
if (s) free (s);
s = NULL;
idx++;
}
return 0;
}
<强>输出强>
$ ./bin/split_string
The strings in the array:
The cat jumped over the lazy dog.
The quick brown fox jumps over a lazy dog.
The little boy exclaimed to see such a sight,
and the dish ran away with the spoon.
enter minumum length for string match : 5
string: The cat jumped over the lazy dog.
jumped : 6
string: The quick brown fox jumps over a lazy dog.
quick : 5
brown : 5
jumps : 5
string: The little boy exclaimed to see such a sight,
little : 6
exclaimed : 9
sight, : 6
string: and the dish ran away with the spoon.
spoon. : 6
答案 2 :(得分:0)
不属于您的模式,但应该有效。
int l = strlen(ar);
char* wordstart = ar;
int wordlen = 0;
for (int i = 0; i <= l; i++)
{
if (ar[i] == ' ' || ar[i] == '\0') // assume a[l] == '\0'
{
if (wordlen > 5)
{
printf("(%.*s)\n", wordlen, wordstart);
}
wordlen = 0;
wordstart = ar + i + 1;
}
else
{
wordlen += 1;
}
}