我只需要删除彼此相邻的重复字符。
示例:如果输入为"heeellooo wooorllldd"
,则输出应为"helo world"
。我当前得到的输出是"helo wrd"
。
这是我的代码。
#include <stdio.h>
#include <string.h>
main()
{
char str[]="heeello wooorld";
redundant(str);
}
void redundant(char *str)
{
int check=0;
int i,j;
char ch;
while(str[check])
{
ch = str[check];
i = j = check + 1;
while(str[i])
{
if(str[i] != ch)
{
str[j] = str[i];
j++;
}
i++;
}
str[j]='\0';
check++;
}
printf("String after removing duplicates : %s\n",str);
}
我一直在寻找一种简约的解决方案。纯娱乐。
void redundant(char *str) {
int lastch = -1; /* last read character */
char* inpp = str; /* pointer to input location */
char* outp = str; /* pointer to output location */
while (*inpp != '\0') {
if (*inpp != lastch) {
*outp++ = lastch = *inpp;
}
inpp++;
}
*outp = '\0';
printf("String after removing duplicates : %s\n", str);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句