繁体   English   中英

从c中的输入字符串中删除字符

[英]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);

     }

我不会为您编写代码,因为您提供的示例代码确实是一个最小的示例,但是您应该执行以下操作:

  1. removeString()函数签名(及其主体)更改为removeString(char* your_string, int where_to_start, int how_much_to_cut) 请注意,在C中, char[]等效于char* ,在您的情况下,最好将char*传递给函数,因为您将拥有可变长度的字符串。
  2. 使用strlen()函数计算传递给removeString()函数的字符串(即char* )的长度。 您可以根据以这种方式计算出的长度对参数进行错误检查。
  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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM