Arrays c程序中按某个字符拆分字符串
我有一个字符串“Hello;World”,我正试图使用一个c程序将这个字符串拆分为组件Hello和World,基本上是在;处拆分字符串 以下是我试图实现这一目标的代码:Arrays c程序中按某个字符拆分字符串,arrays,c,string,split,Arrays,C,String,Split,我有一个字符串“Hello;World”,我正试图使用一个c程序将这个字符串拆分为组件Hello和World,基本上是在;处拆分字符串 以下是我试图实现这一目标的代码: int main() { char* buffer = "Hello;World"; char store_hello[10], store_world[10]; int total_read; total_read = sscanf(buffer, "%s;%s&
int main() {
char* buffer = "Hello;World";
char store_hello[10], store_world[10];
int total_read;
total_read = sscanf(buffer, "%s;%s" , store_hello, store_world);
printf("Value in first variable: %s",store_hello);
printf("\nValue in second variable: %s",store_world);
return 0;
}
我应该能够设置以下输出:
Value in first variable: Hello
Value in second variable: World
但是我没有得到这个输出。如何调整程序以获得所需的输出?您可以使用
%[^;]
说明符,而不是%s
说明符,使sscanf()
扫描到下一个分号
total_read = sscanf(buffer, "%[^;];%s" , store_hello, store_world);
也不要忘记删除一个额外的空间
printf("\nValue in second variable: %s",store_world);
假设我有一个字符串“Hello;Word;World”。如何使用sscanf?
const char*str=“Hello;Word;World”分离这些组件;字符c[3][128];sscanf(str,“%[^;]%[^;];%s”,c[0],c[1],c[2])代码>有关此主题的另一个问题。假设我有一个字符串“Hello;World:Hello World Now”。如果我想用分号分隔这个字符串,这样我就有了字符串“Hello”、“World”和“Hello World Now”?sscanf(str,“%[^;]%[^:]:%s”,c[0],c[1],c[2])我的意思是说字符串是“Hello;World;Hello World Now”。我正在尝试将此字符串拆分为“Hello”、“World”、“Hello World Now”。不幸的是,我只收到字符串“你好”,“世界”,“你好”。在最后一个字符串中,我如何确保获得所有单词,即使它们被空格分隔,而不仅仅是第一个单词?