[英]remove all occurences of a character in C string - Example needed
InputString: "I am unwell" "We need to go to the doctor" "How long will it take?"
。
OutputString: I am unwell We need to go to the doctor How long will it take?
该字符串需要清除所有出现的char "
。我可以想到以下方法
"
重复步骤1和2,直到strchr()返回NULL指针。
我认为这是解决此问题的非常无效的方法。 我需要知道,是否还有其他方法可以实现? 伪代码或实际代码都将受到赞赏。
for (s=d=str;*d=*s;d+=(*s++!='"'));
您可以通过访问字符串的每个字符一次来完成此操作。 您基本上可以将字符串复制到其自身上,而跳过“”字符:
伪代码:
码:
// assume input is a char* with "I am unwell\" \"We need to go..."
char *src, *dest;
src = dest = input; // both pointers point to the first char of input
while(*src != '\0') // exit loop when null terminator reached
{
if (*src != '\"') // if source is not a " char
{
*dest = *src; // copy the char at source to destination
dest++; // increment destination pointer
}
src++; // increment source pointer
}
*dest = '\0'; // terminate string with null terminator
// input now contains "I am unwell We need to go..."
更新 :修复了代码中的一些错误
创建新的字符串,而不是将字符“就地”移动以覆盖要删除的字符。
通过将每个有效字符复制一次,可以最大程度地减少复制的字符数。 使用原始方法,将字符串末尾的字符复制n次,其中n是其前面的无效字符数。
如果您的字符串不是很大,那么显而易见的答案是使用单独的字符串。 一个循环,直到获得\\ 0(字符串结尾)为止。进行一个循环(为您提供O(n)),并进行比较以检查字符串的当前位置是否为所讨论的字符(再次为O(n))。
在所有 :
s1 = original array
s2 = new array to store the final result
c = character in question.
current_pointer = 0
new_pointer =0
while(s1[current_pointer] != '\0') {
ele = s1[current_pointer] ;
if( ele != c) {
s2[new_pointer++] = ele
}
current_pointer++
}
请注意,此方法仅在字符串大小较小时起作用。 随着字符串大小的增加,我们需要寻找更好的方法。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.