用中橫線代替C++中的空格


在這個C++程式中,字串中的空格將被中橫線代替。首先,確定字串的長度的依據是cstring類的length()函式,然後透過遍歷字串並用中橫線填充句子的空格,具體如下。

示例

 線上演示

#include <cstring>
#include <iostream>
using namespace std;
int main(){
   // raw string declaration
   string str = "Coding in C++ programming";
   cout<<"Normal String::"<<str<<endl;
   for (int i = 0; i < str.length(); ++i) {
      // replacing character to '-' with a 'space'.
      if (str[i] == ' ') {
         str[i] = '-';
      }
   }
   // output string with '-'.
   cout <<"Output string::"<< str << endl;
   return 0;
}

輸出

當用戶輸入的字串如下時,程式的輸出將如下所示,使用中橫線修改:

Normal String::Coding in C++ programming
Output string::Coding-in-C++-programming

更新於:2019年11月29日

2K+ 瀏覽

開啟你的 事業生涯

完成課程獲得認證

立即開始
廣告