[英]Removing characters from an input string in c
我的目标是从C中的字符串中删除用户定义的字符数。
该代码要求用户输入一个字符串,指示他们要删除的字符的开头,并指示他们要从该位置删除多少个字符,然后代码显示结果。
我希望那里的人能提供完成所需功能和分步信息的代码,因为我昨天才开始编码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a,b;
char text[20];
char new_sentence[20];
int how_much;
void removeString(char* text, int b, int how_much);
int main(void)
{
printf("\nEnter your sentence: ");
gets(text);
printf("\nWhere to start: ");
scanf("%d",&a);
printf("\nHow many characters do you want to remove: ");
scanf("%d",&how_much);
removeString(char* text, int b, int how_much);
printf("\nNew sentence: %s",text);
return 0;
}
void removeString(char* text, int b, int how_much)
{
how_much = b - a;
memmove(&text[a], &text[b],how_much);
}
我不会为您编写代码,因为您提供的示例代码确实是一个最小的示例,但是您应该执行以下操作:
removeString()
函数签名(及其主体)更改为removeString(char* your_string, int where_to_start, int how_much_to_cut)
。 请注意,在C中, char[]
等效于char*
,在您的情况下,最好将char*
传递给函数,因为您将拥有可变长度的字符串。 strlen()
函数计算传递给removeString()
函数的字符串(即char*
)的长度。 您可以根据以这种方式计算出的长度对参数进行错误检查。 realloc()
的char* your_string
或malloc()
新的字符串和从removeString()
函数返回它。 编辑:
您可以在下面看到问题的解决方案:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 20
char* removeString(char* text, int where_to_start, int how_much)
{
// You should consider all the special (invalid) cases here
// I'm demonstrating how to handle common case
size_t len = strlen(text);
char* new_string = (char*) malloc(sizeof(char) * len - how_much);
memcpy(new_string, text, where_to_start);
memcpy(new_string+where_to_start, text+where_to_start+how_much, len-where_to_start-how_much);
return new_string;
}
int main(void)
{
int a,b;
char buffer[MAX_LEN];
printf("Enter your sentence:\n");
scanf("%s", buffer);
printf("Where to start:\n");
scanf("%d",&a);
printf("How many characters do you want to remove:\n");
scanf("%d",&b);
char* removed = removeString(buffer, a, b);
printf("New sentence: %s\n", removed);
free(removed);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.