请问将多个字符加到一个字符串里有好看点的写法吗?
就比如下面这种(我写的太丑了三种方法还都不对)
#include
#include
using namespace std;
int main()
{
char a = 'a', b = '1', c = '/';
string s = "a1/bcd";
string ans0 = s[0] + s[1] + s[2] ;
string ans1 = to_string(a) + to_string(b) + to_string(c);
string ans2;
ans2 += to_string(s[0]) + to_string(s[1]) + to_string(s[2]);
cout << ans0 <<" " <" " << ans2 << endl;
}
使用stringstream类
#include <iostream>
#include <sstream>
using namespace std;
int main() {
char c1 = 'a';
char c2 = 'b';
char c3 = 'c';
ostringstream oss;
oss << c1 << c2 << c3;
string s = oss.str();
cout << s << endl;
return 0;
}
2.使用字符串拼接方式
#include<iostream>
using namespace std;
int main() {
char c1 = 'a';
char c2 = 'b';
char c3 = 'c';
string s = "";
s += c1;
s += c2;
s += c3;
cout << s << endl;
return 0;
}
可以使用字符串拼接的方式来将多个字符加到一个字符串里。
例如:
string s = "";
s += 'a';
s += '1';
s += '/';
cout << s << endl; // 输出:a1/
也可以使用字符串流来实现:
stringstream ss;
ss << 'a' << '1' << '/';
string s = ss.str();
cout << s << endl; // 输出:a1/
另外,如果要将字符转换成字符串,可以直接使用字符串流:
stringstream ss;
char a = 'a', b = '1', c = '/';
ss << a << b << c;
string s = ss.str();
cout << s << endl; // 输出:a1/
我们可以通过整体逆置的做法,将整个顺序表逆置,然后分别对于两个线性表采用逆置方法
void Reverse(SqList &L, int from, int to) {
int i,temp;
for(i=0;i<(to-from+1)/2;i++)
{
temp=L.data[from+i];
L.data[from+i]=L.data[to-i];
L.data[to-i]=temp;
}
}
void Converse(SqList &L, int n, int p)
{
Reverse(L.data,0,p-1);
Reverse(L.data,p,n-1);
Reverse(L.data,0,n-1);
}