標籤:
字串的操作多用用就行了。
在字串相關操作中,進行字面值的處理需要用庫函數,"="操作的是儲存字串的地址(基本類型)。
1、C中字串的賦值
2、C中字串長度和大小比較
3、C中字串拼接
4、C中字串的拆分
4、C中字串與其他類型轉化
sprintf()->其他格式轉成字串 和 sscanf()->字串轉成其他格式;
幾個小練習:
1、字串中去掉重複的字母:
int judge[52]={0};string derepeat(string str){ string str_change; for(iterator it=str.begin(); it!=str.end(); ++it){ if(*it-‘a‘<26 && !judge[*it-‘a‘] && *it-‘a‘>=0 ){ //如果用strcpy(),怎麼寫
str_change+=*it; judge[*it-‘a‘]=1; } else if(*it-‘A‘<26 && !judge[26+*it-‘A‘] && *it-‘A‘>=0){ str_change+=*it; judge[26+*it-‘A‘]=1; } else if( (*it-‘Z‘>0 && *it-‘a‘<0) || *it-‘A‘<0 || *it-‘z‘ >0)
str_change+=*it; } return str_change;}
2、字串壓縮,輸入:asdddddwerrreeeww 輸出:as5dwe3r3e2w
string string_reduce(string str){ string str_change; ostringstream oss; for(string::iterator it=str.begin(); it!=str.end(); ++it){ int count=1; for(; *it==*(it+1) && it!=str.end(); ){ //iterator重載了關係運算子 ++it; ++count; } if(1==count){ //實現方法很多,這裡複習下IO流的用法,也容易理解 oss << *it; } else { oss << count << *it; //格式化成字串 } } str_change = oss.str(); //c++的string重載了賦值運算子; return string_change;}
3.字元全排列,輸入:abc(預設不重複,重複的可以去重) 輸出:abc acb bac bca cab cba
全排列可以看做是兩位置交換而來;
void perm(char* pstr, char* pbegin){ if(*pbegin == ‘\0‘) printf("%s\n",pstr); else{ for(char* p_ch = pbegin; *p_ch != ‘\0‘; p_ch++){ swap(*pbegin,*p_ch); perm(pstr, pbegin+1); swap(*pbegin,*p_ch); } }
}
字串相關操作