c++ 字符串去重

需求

  • 编写一个字符串过滤函数,若字符串出现多个相同的字符,将不是首次出现的字符过滤掉。

输入:"apache" 输出:"apche"
输入:"google" 输出:"gle"

  • 代码实现
	#include <iostream>
	#include <cassert>
	#include <memory.h>
	using namespace std;

	// 26个标志位 代表着每个字母出现与否 出现后置1
    bool g_flag[26];
    void stringFilter(const char *pInputString, long lInputLen, char *pOutputStr)
    {
        assert(pInputString != NULL);
        int i = 0 ;
        if(pInputString == NULL || lInputLen <= 1)
        {
            return;
        }
        const char *p = pInputString;
        while(*p != '')
        {
            if(g_flag[(*p - 'a')])
            {
                // 不是第一次出现 继续下一个
                p++;
            }
            else
            {
                // 将第一次出现的字母保存
                pOutputStr[i++] = *p;
                // 并将其代表的唯一标准位 置1
                g_flag[*p - 'a'] = 1;
            }
        }
        pOutputStr[i] = '';
    }
    int main(int argc, char const *argv[])
    {
        // memset将初始化指针
        memset(g_flag, 0, sizeof(g_flag));
        // 测试用
        char input[] = "google";
        char *output = new char[strlen(input) + 1];
        stringFilter(input, strlen(input), output);
        cout << output << endl;
        delete output;
        return 0;
    }

1.'a'和"a"是两个不同的东西,前者的类型是char,后者的类型是const char*

原文地址:https://www.cnblogs.com/zhjj/p/6671163.html