PfA*_*nio 7 c++ string function
#include <iostream>
#include <string>
using namespace std;
string wordB(string input);
int main() {
//ask for word
cout << "Enter a word\n";
//get word
string input = "";
cin >> input;
//return with b in between all letters
cout << wordB(input);
cout << endl << input;
}
string wordB(string str) {
string rString = "";
for (unsigned i = 0; i < str.length(); ++i) {
rString += "B" + str.at(i);
}
cout << endl << rString;
return rString;
}
Run Code Online (Sandbox Code Playgroud)
试图显示用户输入的字在每个字符之间有字母"B".当我用这个词运行时,"join"我会回来"trtr".
"B" + str.at(i);不会做你认为它做的事情; 它不是字符串conctatenation.它说:取一个char*指向字符串文字开头的指针"B",使其等于字符的ASCII代码的字符数str.at(i),并将结果指针视为指向以空字符结尾的字符串.除非str.at(i)碰巧'\x0'或'\x1'(不太可能),否则您的程序会表现出未定义的行为.
有许多不同的方法可以做你想要的.这是一个:
rString.push_back('B');
rString.push_back(str[i]);
Run Code Online (Sandbox Code Playgroud)