需求
- 編寫一個字符串過濾函數,若字符串出現多個相同的字符,將不是首次出現的字符過濾掉。
輸入:"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 != '\0')
{
if(g_flag[(*p - 'a')])
{
// 不是第一次出現 繼續下一個
p++;
}
else
{
// 將第一次出現的字母保存
pOutputStr[i++] = *p;
// 並將其代表的唯一標准位 置1
g_flag[*p - 'a'] = 1;
}
}
pOutputStr[i] = '\0';
}
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*