有没有办法在 C 中将字符串拆分为多个字符?
C 中是否有一种方法可以在分隔符长度超过一个字符的情况下分割字符串(使用 strtok 或任何其他方式)?我正在寻找这样的东西:
char a[14] = "Hello,World!";
char *b[2];
b[0] = strtok(a, ", ");
b[1] = strtok(NULL, ", ");
我希望它不会分割字符串,因为逗号和 W 之间没有空格。有没有办法做到这一点?
Is there a way in C to split a string (using strtok
or any other way) where the delimiter is more than one character in length? I'm looking for something like this:
char a[14] = "Hello,World!";
char *b[2];
b[0] = strtok(a, ", ");
b[1] = strtok(NULL, ", ");
I want this to not split the string because there is no space between the comma and the W. Is there a way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以重复调用
substr
来查找出现的情况边界字符串并沿着结果分割。找到结果后,将指针前进子字符串的长度并再次搜索。You could just repeatedly call
substr
to find occurrences of your boundary string and split along the results. After you found a result, advance the pointer by the length of the substring and search again.您可以使用 char * strstr(const char *haystack, const char *needle) 在字符串中定位分隔符字符串。
You can use
char * strstr(const char *haystack, const char *needle)
to locate your delimiter string within your string.也许是这样的?不保证可以编译。 ;)
Something like this maybe? No guarantees that this compiles. ;)