用中横线代替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+ 浏览

开启你的 事业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.