有没有办法将 scanf 的分隔符设置为非字母的任何内容?
我的意思是,假设我有一个来自标准输入的输入:abc123def。从技术上讲,它只是一个字符串,但我想将其视为由非字母字符分隔的 2 个字符串(在本例中为 123)。
我找到了一种设置自定义分隔符的方法,但在这里,它的范围很大(数字字符、特殊字符、空格、制表符......任何不在 A..Za..z 范围内的东西)。
举个例子,这是我想做的事情:
#include <stdio.h>
int main()
{
char str[100];
while (scanf("%s", str) == 1)
{
printf("%s\n", str);
}
return(0);
}
上面的代码只使用空格作为分隔符(我认为)。但我希望它使用任何非字母字符作为分隔符。所以当输入是:
Hi12There..你好
它会输出:
你好
那里
你好
更新:好的,我找到了解决方案。它使用 strtok 函数来完成这项工作,但方式不同。代码如下所示:
#include <stdio.h>
#include <string.h>
int main()
{
int i, len;
char str[100], *word;
while (gets(str))
{
len = strlen(str);
for (i=0; i < len; i++) // Replacing anything non alphabetic with space
{
if ( !(((str[i] >= 'A') && (str[i] <= 'Z')) || ((str[i] >= 'a') && (str[i] <= 'z'))) )
{
str[i] = ' ';
}
}
word = strtok(str, " ");
while (word != NULL)
{
printf("%s\n", word);
word = strtok(NULL, " ");
}
}
return(0);
}
它完成了这项工作,但我想知道我是否可以在从标准输入中获取字符串的同时直接完成它。
干杯。
最佳答案
您可以使用字符序列格式说明符:
char s1[128], s2[128];
if(sscanf("abc123def", "%127[A-Za-z]%*[0-9]%127[A-Za-z]", s1, s2) == 2)
{
printf("got '%s' and '%s'\n", s1, s2);
}
关于c - 在 C 中,如何将 scanf 的分隔符设置为非字母的任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19265197/