例:
輸入字符串:qweqweasdlmn
輸出字符串:qweasdlmn
#include <iostream> #include<cstring> using namespace std; string remove_same(string str) { size_t subpos,sublen; string temp_str; temp_str.append(str,0,1); for(subpos=1;subpos<str.length();subpos++) { for(sublen=0;sublen<temp_str.length();sublen++) { if(str[subpos]==temp_str[sublen]) break; } if(sublen==temp_str.length()) temp_str.append(str,subpos,1); } return temp_str; } int main() { string instr; cout<<"輸入一個字符串"<<endl; getline(cin,instr);//防止遇到空格就結束 string new_str=remove_same(instr); cout<<new_str<<endl; }
remove_same子函數用來實現對重復字符的判斷,並得到沒有重復字符的結果字符串
思路:創建一個temp_str用來存放結果字符串,最開始temp_str里面只有instr的第一個字符,sub_pos用來記錄instr里下一個要進行判斷的字符的位置,除了第一個字符,每個instr的字符都要進行判斷,判斷的方式是將每個字符與temp_str里的每個字符進行比較,若沒有重復的,則將該字符添加到temp_str的后面,若有重復的,跳到下一個字符判斷,直到所有的字符都判斷完畢,最后存入temp_str的字符一定是沒有重復元素的,輸出即可。
程序運行結果:第二行是輸入字符串,第三行是去除重復字符串的結果,可以看到重復空格也被去除了。