如何从字符范围内删除字符

时间:2015-06-12 16:48:59

标签: c

我想删除字符范围内的字符。我该如何实施这个程序? c中是否有任何预定义的函数来执行此操作?

我们说我有:

C is an imperative (procedural) language.
blah blah blah /*this is a comment*/

我希望我的输出类似于:

C is an imperative language.
blah blah blah 

如果这个问题含糊不清,我真的很抱歉。 任何帮助都会受到重视。提前谢谢。

2 个答案:

答案 0 :(得分:1)

#include <stdio.h>
#include <string.h>

void strdel_with_range(char *s, char *from, char *to){
    //code of validation here (omitted)
    memmove(from, to+1, strlen(to+1)+1);//strlen(to+1)(length of rest)+1(null-terminator)
}

int main(void){
    char data[][64] = {
        "C is an imperative (procedural) language.",
        "blah blah blah /*this is a comment*/"
    };
    char *start, *end;
    start = strchr(data[0], '(');
    end   = strchr(start, ')');
    strdel_with_range(data[0], start, end+1);//+1 : point to space after ')'

    start = strstr(data[1], "/*");
    end   = strstr(start, "*/");
    strdel_with_range(data[1], start, end+1);//+1 : point to '/' (end point to '*')
    puts(data[0]);//C is an imperative language.
    puts(data[1]);//blah blah blah
    return 0;
}

答案 1 :(得分:0)

我编写了一个函数document.getElementById("txtSearch").addEventListener("keyup", function (event) { if (event.keyCode==13) { document.getElementById("#btnSearch").click(); } }); ,它创建并返回一个新字符串,该字符串不包含分隔符之间指定的部分。分隔符也是字符串。

remove_string_between_delimiters

输出:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * remove_string_between_delimiters(const char * str, size_t length, const char * first_delimiter , const char * second_delimiter) {

  char * first = strstr(str, first_delimiter);
  char * second = strstr(str, second_delimiter);
  char * new_string = NULL;
  size_t to_remove = 0, new_string_size = 0;
  size_t length_first_half = 0;
  size_t length_second_half = 0;


  if (  first == NULL || second == NULL ||  second - first < 0) {
    return NULL;
  }

  to_remove = second - first;

  new_string_size =  length - to_remove ;
  new_string = malloc(new_string_size);

  length_first_half = first-str;
  length_second_half = length - (second - str) - strlen(second_delimiter);


  memset(new_string, 0, new_string_size);
  memcpy(new_string, str, length_first_half);
  memcpy(new_string + length_first_half, second + strlen(second_delimiter), length_second_half);

  return new_string;
}

int main() {
  const char * test = "This is a test /* sdfsfs */";
  printf("%s\n", remove_string_between_delimiters( test, strlen(test), "/*", "*/" ));
}

分隔符可以是任何东西。