简体   繁体   English

从C字符串中删除charAt

[英]Removing charAt from c string

I am trying to write simple removeAt(char* str, int pos) in C, but confused by result. 我正在尝试用C语言编写简单的removeAt(char * str,int pos),但对结果感到困惑。

char c[] = "abcdef";
char* c1 = removeAt(c, 3);

cout << c1;

If I am doing it in this way: 如果我以这种方式这样做:

static char* removeAt(char* str, int pos)
{
   int i = 0;

   for(i = pos; str[i] != '\0'; i++)
   {
       str[i] = str[++i];
   }

   str[i] = '\0';

   return str;
}

string stays the same "abcdef"; 字符串保持相同的“ abcdef”;

If I am doing: 如果我在做:

static char* removeAt(char* str, int pos)
{
 int i, k =0;

for(i = pos, k = pos;  str[i] != '\0'; i++)
{
   str[i] = str[++k];
}

str[i] = '\0';

return str;
}

does work as intended. 确实按预期工作。

In this loop 在这个循环中

for(i = pos; str[i] != '\0'; i++)
{
    str[i] = str[++i];
}

You change the value of i by doing i++ , so you end up missing a character every two, or something similar. 您通过执行i++更改i的值,因此最终每两个字符或类似字符丢失一个字符。 Change i++ to i+1 . i++更改为i+1

EDIT: By the way, the line 编辑:顺便说一句

str[i] = str[++i] 

is undefined behaviour, since it's not specified when the increment will occur (before or after evaluating the left side?). 是不确定的行为,因为在递增发生时(在评估左侧之前还是之后)未指定。 If the right side is evaluated first then your code would be 如果首先评估右侧,则您的代码将是

i++;
str[i] = str[i];

Effectively doing nothing, as you observe. 如您所见,实际上什么也没做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM