我会使用strchr
,但我想找到一个看起来像这样的序列:“%c”-包括空格。
但是我有两个问题:
目标是将未定义数量的字符串(组合起来,不要超过缓冲区大小)读入单个缓冲区,直到找到一个用空格分隔的字符:
char buf[50];
sscanf("string1 string2 string3 M other input", "%[^ %c ]", buf);
printf("%s", buf); //This would output "string1 string2 string3"
答案 0 :(得分:1)
strchr可以找到字符串中字符的第一个出现位置。可以通过比较第一个非空间ch和第二个非空间ch之间的距离来找到图案的末端。
#include <stdio.h>
#include <string.h>
// The input buffer must match the pattern "string string ... ch"
const char* get_endof_pattern(const char *buffer)
{
const char *first_non_space = buffer;
const char *second_non_space = strchr(first_non_space, ' ') + 1;
if (!second_non_space)
return NULL;
while (second_non_space - first_non_space > 2) {
first_non_space = second_non_space;
second_non_space = strchr(first_non_space, ' ') + 1;
if (!second_non_space)
return NULL;
}
return first_non_space;
}
答案 1 :(得分:1)
strspn
和strcspn
可用于查找由空格包围的单个字符。
#include <stdio.h>
#include <string.h>
int main( void) {
char *text[] = { "string1 string2 string3 M other input"
, "string1 string2 string3 other input M"
, "M string1 string2 string3 other input M"};
int offset = 0;
int spaces = 0;
int length = 0;
for ( int each = 0; each < 3; each++) {
offset = 0;
do {
spaces = strspn ( text[each] + offset, " ");//consecutive spaces
offset += spaces;
length = strcspn ( text[each] + offset, " ");//consecutive not space
offset += length;
} while ( 1 != length && 0 != *(text[each] + offset));
if ( 1 == length) {
printf ( "[%.*s]\n", offset - ( spaces + length), text[each]);
}
else {
printf ( "[%s]\n", text[each]);
}
}
return 0;
}