字串相關操作

來源:互聯網
上載者:User

標籤:

字串的操作多用用就行了。

在字串相關操作中,進行字面值的處理需要用庫函數,"="操作的是儲存字串的地址(基本類型)。 

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);          }      }  
}

 

字串相關操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.