当我
时,我该怎么办呢?string s = ".";
如果我这样做
cout << s * 2;
是否与
相同cout << "..";
答案 0 :(得分:17)
std :: string有一个
形式的构造函数std::string(size_type count, char c);
将重复该角色。例如
#include <iostream>
int main() {
std::string stuff(2, '.');
std::cout << stuff << std::endl;
return 0;
}
将输出
..
答案 1 :(得分:9)
不,std::string
没有operator *
。您可以将(char,string)添加到其他字符串。看看这个http://en.cppreference.com/w/cpp/string/basic_string
如果您想要这种行为(没有建议),您可以使用类似这样的内容
#include <iostream>
#include <string>
template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(const std::basic_string<Char, Traits, Allocator> s, size_t n)
{
std::basic_string<Char, Traits, Allocator> tmp = s;
for (size_t i = 0; i < n; ++i)
{
tmp += s;
}
return tmp;
}
template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(size_t n, const std::basic_string<Char, Traits, Allocator>& s)
{
return s * n;
}
int main()
{
std::string s = "a";
std::cout << s * 5 << std::endl;
std::cout << 5 * s << std::endl;
std::wstring ws = L"a";
std::wcout << ws * 5 << std::endl;
std::wcout << 5 * ws << std::endl;
}
http://liveworkspace.org/code/52f7877b88cd0fba4622fab885907313
答案 2 :(得分:5)
没有预定义的*
运算符会将字符串乘以int
,但您可以定义自己的运算符:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string operator*(const string& s, unsigned int n) {
stringstream out;
while (n--)
out << s;
return out.str();
}
string operator*(unsigned int n, const string& s) { return s * n; }
int main(int, char **) {
string s = ".";
cout << s * 3 << endl;
cout << 3 * s << endl;
}
答案 3 :(得分:5)
我使用运算符重载来模拟c ++中的这种行为。
#include <iostream>
#include <string>
using namespace std;
/* Overloading * operator */
string operator * (string a, unsigned int b) {
string output = "";
while (b--) {
output += a;
}
return output;
}
int main() {
string str = "abc";
cout << (str * 2);
return 0;
}
输出: abcabc
答案 4 :(得分:1)
字符串不能成倍增加。
如果s是char
'.' //this has 46 ascii-code
然后
cout << (char)((int)s * 2);
会给你
'/' //this has 92 ascii-code
答案 5 :(得分:0)
它们不能被倍增,但我认为你可以编写自己的函数来做到这一点,比如 -
#include <iostream>
#include <string>
std::string operator*(std::string s, size_t count)
{
std::string ret;
for(size_t i = 0; i < count; ++i)
{
ret = ret + s;
}
return ret;
}
int main()
{
std::string data = "+";
std::cout << data * 10 << "\n";
}
虽然这可能不是最好的主意,但对于那些看到代码并且没有预料到这一点的人来说会非常混乱,
答案 6 :(得分:0)
您可以这样做:
#include <iostream>
using namespace std;
int main()
{
string text,new_text;
int multiply_number;
cin>>text>>multiply_number;
/*First time in for loop:new_text=new_text+text
new_text=""+"your text"
new_text="your text"
Secound time in for loop:new_text=new_text+text
new_text="your text"+"your text"
new_text="your textyour text"...n times */
for(int i=0;i<multiply_number;i++){
new_text+=text;
}
cout<<new_text<<endl; // endl="\n"
system ("pause");
return 0;
}
在python中,您可以像这样乘以字符串:
text="(Your text)"
print(text*200)