我试图将以下字符串分成三个单独的变量,即 a、b 和 c:
" mov/1/1/1,0 STR{7}, r7"
每个都需要保存字符串的不同部分,例如:
a = "mov/1/1/1,0"
b = "STR{7}"
c = "r7"
每个命令之间可以有空格或制表符;这使得这段代码部分变得更加棘手。
我尝试使用 strtok
进行字符串操作,但没有成功。
char command[50] = " mov/1/1/1,0 STR{7}, r7";
char a[10], b[10], c[10];
char * ptr = strtok(command, "\t");
strcpy(a, ptr);
ptr = strtok(NULL, "\t");
strcpy(b, ptr);
ptr = strtok(NULL, ", ");
strcpy(c, ptr);
但这会让事情变得非常困惑,因为变量 a、b
和 c
保存的值超出了应有的值,从而导致程序崩溃。
输入可能有所不同:
" mov/1/1/1,0 STR{7}, r7"
"jsr /0,0 PRTSTR"
"mov/1/1/0,0 STRADD{5}, LASTCHAR {r3} "
其中 a、b 和 c 的值更改为给定字符串的不同部分。
有人告诉我,使用 sscanf 比 strtok 更安全,但我不确定为什么以及它如何帮助我。
我非常高兴听到您的意见!
最佳答案
这应该可以解决问题:
sscanf(命令, "%s,%s,%s", &a, &b, &c)
从 scanf 手册页来看,%s
会吃掉空格,无论是空格还是制表符:
s : Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
关于c - 在 C 中使用 strtok/sscanf 进行字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18293159/