我知道这是一个简单的问题,但我找不到答案。
我有这个字符串:
"M1[r2][r3]"
我想只获取"M1"
,我正在寻找strchr()
之类的内容
获取字符串并停留在char
的函数。
答案 0 :(得分:4)
如果使用strtok
和"["
作为分隔符呢?
#include <string.h> /* for strtok */
#include <stdio.h> /* for printf */
int main()
{
char str[] = "M1[r2][r3]"; // str will be modified by strtok
const char deli[] = "["; // deli could also be declared as [2] or as const char *. Take your pick...
char *token;
token = strtok(str, deli); // can also call strtok(str, "["); and not use variable deli at all
printf("%s", token); // printf("%s", str); will print the same result
/* OUTPUT: M1 */
return 0;
}
答案 1 :(得分:1)
使用strtok()
和字符停止(在您的情况下为[
的分隔符),如下所示:
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="M1[r2][r3]";
printf ("Getting M1 from \"%s\":\n",str);
strtok (str,"[");
if (str != NULL)
printf ("%s\n",str);
return 0;
}
输出:
Getting M1 from "M1[r2][r3]":
M1
但是,如果您知道子字符串的长度,则应该看到Get a substring of a char*。
答案 2 :(得分:0)
像这样使用sscanf()
:
char subStr[3];
sscanf("M1[r2][r3]", " %2[^[]", subStr);
其中[^[]
表示除[
之外的字符,2表示写入子字符串的字符串长度(等于subStr
的大小 - 1,因此该空间为NULL终止符可用。)
正如BLUEPIXY建议的那样。
答案 3 :(得分:0)
类似于strchr()的函数,它获取字符串和char停止。
如果只需要打印子字符串,请使用strcspn()
查找首次出现'['
时的偏移量(如果未找到则结束)。这不会改变源字符串。
const char *s = "M1[r2][r3]";
printf("%.*s\n", strcspn(s, "["), s);
输出
M1