So, I am trying to add and remove characters from an array. I have an add_to_array function which works fine. It prints out exactly what it should. However, I can't seem to remove a character from the end of my array. My code at the attempt was:
因此,我尝试添加和删除数组中的字符。我有一个add_to_array函数,它运行良好。它打印出了它应该做什么。然而,我似乎无法从数组的末尾移除一个字符。我尝试的代码是:
void delete_array(char *q, char f)
{
char *blah = q;
while(*blah != '\0')
{
blah--;
}
*blah = f;
blah--;
*blah = '\0';
}
My code for my add_to_array was exactly the same except it was blah++ and I thought removing a character would just be the opposite. It compiles but it prints "segmentation fault (core dumped)" as an output. Where am I going wrong? Thank you for any suggestions/help.
我的add_to_array的代码完全相同,只不过它是什么都没有,我认为删除一个字符正好相反。它编译,但它打印“分割错误(核心转储)”作为输出。我哪里出错了?谢谢你的建议/帮助。
2 个解决方案
#1
1
like this:
是这样的:
#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;
}
In the case of deletion of the character of the particular position you need to include the position in the parameter.
在删除特定位置的字符时,您需要在参数中包含位置。
#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;
}
#2
-1
The below code shows you how you can remove a character in a string.
下面的代码向您展示了如何删除字符串中的字符。
void delete_array(char *q, char f)
{
char *blah = q;
char *temp;
while(*blah != '\0')
{
if(*blah == f){
while(*blah != '\0'){
temp = blah;
temp++;
*blah = *temp;
blah++;
}
break;
}
blah++;
}
}
#1
1
like this:
是这样的:
#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;
}
In the case of deletion of the character of the particular position you need to include the position in the parameter.
在删除特定位置的字符时,您需要在参数中包含位置。
#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;
}
#2
-1
The below code shows you how you can remove a character in a string.
下面的代码向您展示了如何删除字符串中的字符。
void delete_array(char *q, char f)
{
char *blah = q;
char *temp;
while(*blah != '\0')
{
if(*blah == f){
while(*blah != '\0'){
temp = blah;
temp++;
*blah = *temp;
blah++;
}
break;
}
blah++;
}
}