从c中的字符串中删除所有重复的字符 [英] removing all repeated characters from string in c
本文介绍了从c中的字符串中删除所有重复的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串中删除所有重复的字符.例如,如果我有:
I want to remove all the repeated characters from a string. For example, if I have:
"abcdabef"
我希望结果是
"cdef"
我已经尝试过使用循环,但是这让我感到困惑.谁能告诉我该怎么做?
I have tried with loops, but it's getting me confusing. Can anyone just tell me how to do this?
这是我到目前为止尝试过的:
Here's what I've tried so far:
#include<stdio.h>
#include<string.h>
main()
{
char s[20],ch,*p;
int i,j,k,cnt;
puts("enter string:");
gets(s);
for(i=0;s[i];i++)
{
ch=s[i];
for(cnt=0,j=0;s[j];j++)
{
if(ch==s[j])
cnt++;
if(cnt>1)
{
for(k=0;s[k]==ch;k++)
{
strcpy(s+k,s+k+1);
if(s[k]==ch)
{k--;}
}
if(s[j-1]==ch)
j--;
}
}
}
puts(s);
}
推荐答案
如果我是你,我只计算字符串中的字符并打印出在字符串中恰好出现一次的字符.
If I were you, I would just count the characters in the string and print out those which appear exactly once in the string.
char buf[BUFSIZE]; // whatever the size is
// get user input
if (!fgets(buf, sizeof buf, stdin))
exit(EXIT_FAILURE); // couldn't fgets()
size_t len = strlen(buf);
int counts[1 << CHAR_BIT] = { 0 };
// count each character
for (size_t i = 0; i < len; i++) {
unsigned char ch = buf[i];
counts[ch]++;
}
// print those which are present exactly once
for (size_t i = 0; i < 1 << CHAR_BIT; i++) {
if (counts[i] == 1) {
printf("%c", (unsigned char)(i));
}
}
这篇关于从c中的字符串中删除所有重复的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文