【发布时间】:2020-05-30 23:55:13
【问题描述】:
我真的想将我的 char 数组中的所有空格 ' ' 更改为 NULL -
#include <string.h>
void ReplaceCharactersInString(char *pcString, char *cOldChar, char *cNewChar) {
char *p = strtok(pcString, cOldChar);
strcpy(pcString, p);
while (p != NULL) {
strcat(pcString, p);
p = strtok(cNewChar, cOldChar);
}
}
int main() {
char pcString[] = "I am testing";
ReplaceCharactersInString(pcString, " ", NULL);
printf(pcString);
}
输出:Iamtesting
如果我只是把printf(p)函数放在前面:
p = strtok(cNewChar, cOldChar);
结果我得到了我需要的东西——但问题是如何将它存储在pcString(直接)?
或者有更好的解决方案来简单地做到这一点?
【问题讨论】:
-
只是为了学习,为什么要将空格转换为空字符?
-
我想解码特定类型的令牌 - 字符串、数字 - 下一个函数需要这个。
-
如果
p最初是NULL怎么办?你不检查这个,strcpy会出现段错误。 -
@CraigEstey 你说得对,我在调试器的确切
strcpy()行上收到了段错误消息。我不确定到底出了什么问题。 -
@AlwaysDissapointed:你不想得到字符串 INULLamNULLtestingNULL,你想要
"I\0am\0testing\0"和字符串实际结尾的一些指示。您可能想要分配一个指针数组并让它们指向单词。