这是我的代码:
#include <stdio.h>
void main(void){
char myString[81];
int x,y,z=0;
while(x<81){
system("cls");
printf("Please input a string 80 characters or less. Press space to enter your string. >>>");
for(y=0;y<x;y++){
printf("%c",myString[y]);
}
myString[x]=getch();
if ((int)myString[x] == 13){
myString[x]="\0";
break;
}
if ((int)myString[x] == 8){
/*Remove Character code here*/
x=x-1;
}
printf("\n");
x=x+1;
z=x;
}
printf("\nYou typed \n");
for(y=0;y<z;y++){
printf("%c",myString[y]);
}
}
我尝试过很多事情。我希望能够在不使用 #include <string.h>
的情况下执行此操作因为这是一个了解代码如何工作以及语言如何创建的实验。不过,我愿意使用函数。我已经尝试过使用一个函数,但它使用了我不理解的代码。我尝试过的其他事情包括memremove()
和myString[x] = " ";
。
请回复一个解决方案和解释,因为我仍然是一个学习程序员。
最佳答案
我认为你必须使用指针。如果你指向要删除的字符的索引,问题就会解决。像这样定义你的数组:
char myString[] = "This is string";
char *pMyString = myString;
然后指向下一个索引而不是您要删除的索引
for (char *pMyString = myString; *pMyString != '\0'; pMyString++)
*pMyString = *(pMyString+1);
*pMyString = '\0';
关于c - 当按下某个键时,如何从字符数组中删除一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45152133/