C++ 程式字串類及其應用程式?


字串是一個字元序列。在 C++ 程式語言中,字串可以用兩種方式定義 −

  • C 樣式字串:將字串視為一個字元陣列。

  • C++ 中的字串類

  • 可以從庫“string”在 C++ 程式中使用字串類。它將字串儲存為記憶體中的一個字元陣列,但將它顯示為一個字串物件給使用者。在 C++ 中,有許多方法支援 C++ 字串類,並且有助於物件的正常功能並提高程式碼效率。

例子

找到一些使用字串的常見字串應用程式 −

#include <bits/stdc++.h>
using namespace std;
bool charcheck(string str) {
   int l = str.length();
   for (int i = 0; i < l; i++) {
      if (str.at(i) < '0' || str.at(i) > '9')
         return false;
   }
   return true;
}
string replacedotWith20(string str) {
   string replaceby = "%20";
   int n = 0;
   while ((n = str.find(" ", n)) != string::npos ) {
      str.replace(n, 1, replaceby);
      n += replaceby.length();
   }
   return str;
}
int main() {
   string num = "3452i";
   if (charcheck(num))
      cout << "string contains only digit" << endl;
   else
      cout<<"string contains other characters too"<<endl;
   string url = "google com in";
   cout << replacedotWith20(url) << endl;
   return 0;
}

輸出

字串也包含其他字元。

google%20com%20in

在使用網路時,以上內容可以提供幫助。

更新於: 08-8-2019

146 瀏覽量

開啟您的職業生涯

修完課程獲得認證

開始吧
廣告
© . All rights reserved.