使用指针而不是索引从字符串中删除字符(在c中)
我需要一个函数来删除索引处字符串中的字符,而不使用括号[],相反,我必须使用指针。我不允许使用memmove或其他功能。这就是我到目前为止所做的:使用指针而不是索引从字符串中删除字符(在c中),c,pointers,C,Pointers,我需要一个函数来删除索引处字符串中的字符,而不使用括号[],相反,我必须使用指针。我不允许使用memmove或其他功能。这就是我到目前为止所做的: void stringDeleteChar(char*s,int索引){ int i=0; char*hold=NULL; 如果(索引>strlen(s)| |索引
void stringDeleteChar(char*s,int索引){
int i=0;
char*hold=NULL;
如果(索引>strlen(s)| |索引<0){
s='\0';
}
否则{
s+=指数;
保持=s+1;
而(i
执行s='\0'
没有效果忽略它并退出函数。但是,索引<0
是错误的,因为您可能也想删除数组的第一个元素:
void stringDeleteChar(char *s, int index){
if (index <= strlen(s) && index >= 0){
for (char* str_pointer = s + index; *str_pointer != '\0'; str_pointer++)
*str_pointer = *(str_pointer + 1);
}
}
您可以看到,
s[i]
相当于*stru指针
您所需要的就是处理,而循环中,s
会在循环内发生变化,因此它不会给您正确的输出,所以只需检查保持作为任何数据,直到\0
else{
s += index+1;
hold = s+1;
putchar(*s);putchar(*hold);
while (*hold){
*s = *hold;
s++;
hold++;
i++;
}
*s = *hold;
}
else{
s += index+1;
hold = s+1;
putchar(*s);putchar(*hold);
while (*hold){
*s = *hold;
s++;
hold++;
i++;
}
*s = *hold;
}