华为:编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉

/*
题目描述(60分):
通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,
若字符串中出现多个相同的字符,将非首次出现的字符过滤掉。
比如字符串“abacacde”过滤结果为“abcde”。
要求实现函数:
void stringFilter(const char *pInputStr, long lInputLen, char *pOutputStr);
【输入】 pInputStr: 输入字符串
lInputLen: 输入字符串长度
【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;
【注意】只需要完成该函数功能算法,中间不需要有任何IO的输入输出
示例
输入:“deefd” 输出:“def”
输入:“afafafaf” 输出:“af”
输入:“pppppppp” 输出:“p”
*/
#include<iostream>
#include<assert.h>
#include<cstring>
using namespace std;
#define N 256
char hash[N]={0};
void stringFilter1(const char *pInputStr, long lInputLen, char *pOutputStr)
{
    int a[26] = {0};
    int pos = 0;
    long i, j;
    const char *p = pInputStr;
    for(i = 0, j = 0; i < lInputLen; i++)
    {
        pos = pInputStr[i] - 'a';
        if(a[pos] == 0)
        {
            a[pos]++;
            pOutputStr[j++] = pInputStr[i];
        }
    }
    pOutputStr[j]='\0';//不要忘记
}
void stringFilter(const char *pInputStr, long lInputLen, char *pOutputStr)
{
    assert(pInputStr!=NULL);
    assert(pOutputStr!=NULL);
    assert(lInputLen>0);
const char *p=pInputStr;
    while(*p!='\0')
    {
        hash[*p]++;
        p++;
    }
//p=pInputStr;
    while(*pInputStr!='\0')//重大错误,因为上一个循环已经把*pInputSt遍历到'\0',所以上一个循环用const char *p=pInputStr;
    {


        if(hash[*pInputStr]>=1)
        {
                hash[*pInputStr]=0;
                *pOutputStr++=*pInputStr++;
        }
        else
        {
                pInputStr++;
        }


    }
    *pOutputStr='\0';
}
int main()
{
    char a[]="afafafaf";
    int n=strlen(a);
    cout<<"a="<<a<<endl;
    cout<<"n="<<n<<endl;
    //char *p=new char(n); 经典菜鸟错误,注意new的括号是方括号
    char *p=new char[n];
    if(p==NULL)
    cout<<"error"<<endl;
    stringFilter1(a,n,p);
    cout<<"p="<<p<<endl;
    delete []p;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值