用中橫線代替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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP