0

我的目标是从 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);

     }
4

1 回答 1

0

我不会为您编写代码,因为您提供的示例代码确实是一个最小的示例,但这些是您应该做的事情:

  1. removeString()将函数签名(及其相应的主体)更改为removeString(char* your_string, int where_to_start, int how_much_to_cut). 请注意,在 Cchar[]中等效于char*并且在您的情况下,最好将 a 传递char*给您的函数,因为您将拥有可变长度的字符串。
  2. 使用函数计算传递给函数strlen()的字符串(即)的长度。您可以根据以这种方式计算的长度对参数进行错误检查。char*removeString()
  3. 请注意,您可能会遇到必须在字符串中间剪切一些字符的情况 - 因此,我将计算结果字符串的长度以及新字符串或新字符串realloc()的长度并从函数中返回。char* your_stringmalloc()removeString()
  4. 您可以按照此网页上的信息将输入参数(字符串、剪切位置、剪切多少字符)添加到您的程序中。

编辑:

您可以在下面看到您的问题的解决方案:

#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;
}
于 2015-05-04T16:43:27.320 回答