所以,我正在尝试从数组中添加和删除字符。我有一个工作正常的 add_to_array 函数。它准确地打印出它应该打印的内容。但是,我似乎无法从数组末尾删除字符。我尝试时的代码是:
void delete_array(char *q, char f)
{
char *blah = q;
while(*blah != '\0')
{
blah--;
}
*blah = f;
blah--;
*blah = '\0';
}
我的 add_to_array 代码完全相同,只是它是 blah++ 并且我认为删除一个字符正好相反。它可以编译,但会打印“段错误(核心转储)”作为输出。我哪里错了?感谢您的任何建议/帮助。
最佳答案
像这样:
#include <stdio.h>
void delete_array(char *str, char ch){
//To remove the specified character from a string
char *to, *from;
for(to = from = str; *from != '\0'; ++from){
if(*from != ch)
*to++ = *from;
}
*to = '\0';
}
int main(void){
char str[] = "application";
delete_array(str, 'p');
printf("%s\n", str);//alication
return 0;
}
<小时/>
如果删除特定位置的字符,您需要在参数中包含该位置。
#include <stdio.h>
void delete_array(char *str, size_t pos){
//Delete the character of the position pos.
char *p;
for(p = str + pos; *p = p[1] ; ++p)
;
}
int main(void){
char str[] = "application";
delete_array(str, 3);
printf("%s\n", str);//appication
return 0;
}
关于c - 如何删除数组中特定位置的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804142/