返回列表 發帖

C++ 字串分割 (一)

本帖最後由 tonyh 於 2022-12-15 19:35 編輯

試將字串 "123.45.6789" 以 "." 作為分割的依據進行分割,並將分割結果存入一陣列。

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. string str="123.45.6789";
  4. int data[50];
  5. stringstream ss;
  6. int n;
  7. int main()
  8. {
  9.     cin.tie(0);
  10.     cin.sync_with_stdio(0);

  11.     //cout<<str<<endl;
  12.     replace(begin(str),end(str),'.',' ');
  13.     //cout<<str<<endl;
  14.     ss<<str;
  15.     int index=0;
  16.     while(ss>>n)
  17.     {
  18.         data[index]=n;
  19.         index++;
  20.     }

  21.     for(int i=0; i<index; i++)
  22.         cout<<data[i]<<endl;

  23.     return 0;
  24. }
複製代碼
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. string str="123.45.6789";
  4. stringstream ss;
  5. int n;
  6. int main()
  7. {
  8.     cin.tie(0);
  9.     cin.sync_with_stdio(0);
  10.     //cout<<str<<endl;
  11.     replace(str.begin(),str.end(),'.',' ');
  12.     //cout<<str<<endl;
  13.     ss<<str;
  14.     while(ss>>n)
  15.         cout<<n<<endl;

  16.     return 0;
  17. }
複製代碼
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. string str="123.45.6789";
  4. stringstream ss;
  5. int n, index=0, data[100001];
  6. int main()
  7. {
  8.     cin.tie(0);
  9.     cin.sync_with_stdio(0);

  10.     replace(str.begin(),str.end(),'.',' ');
  11.     ss<<str;
  12.     while(ss>>n)
  13.     {
  14.         data[index]=n;
  15.         index++;
  16.     }
  17.     for(int i=0; i<index; i++)
  18.         cout<<data[i]<<endl;

  19.     return 0;
  20. }
複製代碼
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     string str="123.45.6789";
  7.     str+=".";
  8.     string res[50];
  9.     int index=0;
  10.     string tmp="";
  11.     for(int i=0; i<str.size(); i++)
  12.     {
  13.          if(str[i]=='.')
  14.          {
  15.              res[index]=tmp;
  16.              tmp="";
  17.              index++;
  18.          }else
  19.          {
  20.              tmp+=str[i];
  21.          }
  22.     }
  23.     for(int i=0; res[i]!=""; i++)
  24.         cout<<res[i]<<endl;
  25.     system("pause");
  26.     return 0;   
  27. }
複製代碼

返回列表