需要写一个C程序来删除彼此相邻重复字符 [英] Need to write a C Program to remove repeated characters adjacent to each other
本文介绍了需要写一个C程序来删除彼此相邻重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只需要去除重复字符是彼此相邻的。
例如:如果输入heeellooo wooorllldd
,输出应该是HELO世界
。我目前得到的输出是HELO WRD
。
这是code,我有。
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;主要()
{
烧焦海峡[] =heeello wooorld
冗余(STR);
}无效冗余(字符*海峡)
{
INT检查= 0;
INT I,J;
焦炭CH; 而(STR [检查])
{
CH = STR【检查】;
I = J =检查+ 1; 而(STR [I])
{
如果(STR由[i]!= CH)
{
海峡[J] = STR [I]
J ++;
} 我++;
} 海峡[J] ='\\ 0';
检查++;
} 的printf(删除重复后的字符串:%S \\ n,STR);
}
解决方案
我一直在寻找一个简约的解决方案。只是为了好玩。
无效冗余(字符* STR){
INT lastch = -1; / *最后一次读取字符* /
字符* INPP = str中; / *指针输入位置* /
字符* OUTP = str中; / *指针输出位置* /
而(* INPP!='\\ 0'){
如果(* INPP!= lastch){
* OUTP ++ = lastch = * INPP;
}
INPP ++;
}
* OUTP ='\\ 0';
的printf(删除重复后的字符串:%S \\ n,STR);
}
I need to remove only the repeated characters that are adjacent to each other.
Example: if the input is "heeellooo wooorllldd"
, the output should be "helo world"
. The output I am currently getting is "helo wrd"
.
This is the code i have.
#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);
}
解决方案
I was looking for a minimalistic solution. Just for fun.
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);
}
这篇关于需要写一个C程序来删除彼此相邻重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文