我试图去掉C中字符串中的所有\
字符。例如,如果字符串是co\din\g
,则应该将字符串转换为coding
。
到目前为止我有密码
for(i = 0; i < strlen(string); ++i){
if(string[i] == '\'){
}
}
这看上去是否有反斜杠。不过,我不知道该怎么做才能去掉反斜杠。我唯一的想法是将下一个字符设置为当前字符,但是,我不知道更改字符串的长度将如何与内存一起工作。
发布于 2018-11-03 18:07:01
这个很管用。因为您只是在删除字符,所以可以将其写回同一字符串。最后,终止'\0'
将移动到较低的索引,而数组的其余部分将被printf
忽略。另外,\
是转义字符,因此要传递\
本身,必须编写\\
。
#include <stdio.h>
void nukechar(char s[], char c)
{
size_t j = 0;
for (size_t i = 0; s[i] != '\0'; ++i) {
if (s[i] != c) {
s[j] = s[i];
++j;
}
}
s[j] = '\0';
}
int main(void)
{
char s[200];
while (fgets(s, 200, stdin) != NULL) {
nukechar(s,'\\');
printf("%s", s);
}
return 0;
}
发布于 2018-11-03 18:02:54
就像这样:
#include <stdio.h>
int main(){
char st[] = "co\\din\\g";
int k = 0;
for (int i = 0; st[i] != '\0'; ++i)
if (st[i] != '\\')
st[k++] = st[i];
st[k] = '\0';
fputs(st, stdout);
return 0;
}
https://stackoverflow.com/questions/53134028
复制相似问题