c - 过滤字符串中连续重复的字符

标签 c string ignore-duplicates

我的代码有什么问题,或者有待改进吗?

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

char * filterdupchar(char* s,int n){
    char *tmp2 = s ;
    char *tmp =(char*)malloc(n*sizeof(char));
    for(int j=0;j<n/2;j++){
        int i=0,p=0;
        while(i<n){
            *(tmp+p) = s[i];
            if(s[i]==s[i+1])
                i = i+2;
            else
                i++;
            p++;
        }
    s = tmp;
   }
    s = tmp2;
    return tmp;
}
int main(){
     char * str= "bbaaan";
     printf("%s",str);
     printf("\n");
     char * strnew;
     strnew = filterdupchar(str,6);
     printf("%s",strnew);
     return 1;
}

结果应该是“ban”,但是附加了一些乱码。 在我的 func 中,是否有必要将 tmp2 提供给 s,我是否需要释放某事?

最佳答案

变化

  • 只需要一个循环和滞后字符就可以完成过滤(上面没有必要复杂)
  • 需要为 tmp.. 分配字符数 + 1(对于 nullchar)
  • 不需要 malloc 转换
  • 将 nullchar 添加到 tmp 的末尾
  • main 应该在成功时返回 0。否则使用它的进程会感到困惑
  • 需要免费的 strnew..
  • 如果您有任何内存问题,请使用 valgrind
  • 连续调用 print 是多余的..

代码

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

char * filterdupchar(char* s,int n)
{
  int from,to; char last;
  char *tmp = malloc((n+1)*sizeof(char));
  from = to = 0;
  last = 0;
  for(from = 0; from < n; from++)
  {
    if(s[from] != last)
    {
      tmp[to] = s[from];
      to++;
    }
    last = s[from];
  }
  tmp[to] = '\0';
  return tmp;
}
int main()
{
  char * str= "bbaaan";
  printf("%s\n",str);
  char * strnew;
  strnew = filterdupchar(str,6);
  printf("%s\n",strnew);
  free(strnew);
  return 0;
}

输出

$ valgrind ./test
==11346== Memcheck, a memory error detector
==11346== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==11346== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==11346== Command: ./test
==11346== 
bbaaan
ban
==11346== 
==11346== HEAP SUMMARY:
==11346==     in use at exit: 0 bytes in 0 blocks
==11346==   total heap usage: 1 allocs, 1 frees, 7 bytes allocated
==11346== 
==11346== All heap blocks were freed -- no leaks are possible
==11346== 
==11346== For counts of detected and suppressed errors, rerun with: -v

笔记

always use a memory checker ( like valgrind ) to test for memory leaks

关于c - 过滤字符串中连续重复的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32303951/

相关文章:

从 R 中的数据框中删除重复的列组合

javascript - ExtJS 将字符串的网格列排序为 float

Java String replaceAll - 以一种奇怪的方式工作\

python - 在一列字符串中搜索多个子串并返回子串类别

从两列中删除重复的 SQL

c - C 中的 mqtt 给出错误 -1

c - 线程已创建但无法相应工作

c - 归并排序循环链表 C

c - 关于空指针和赋值 C