简单字符串连接 [英] Simple string concatenation

查看:131
本文介绍了简单字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Python中有一个字符串 x ='wow',我可以使用 __ add __ 函数,如下:

  x ='wow'
x .__ add __(x)
'wowwow'

我如何在C ++中做到这一点?

  

> std :: string x =wow;
x + x;

创建一个临时字符串,它是 x x 的连接并丢弃结果。要附加到 x ,您将执行以下操作:

  std :: string x =wow; 
x + = x;

注意双引号 ,在C ++中,单引号用于单字符,双引号用于空结尾的字符串文字。



请参阅 std :: string reference。



顺便说一句,在Python中,你通常不会调用 __ add __()方法。 p>

  x ='wow'
x + x

__ add __()方法只是为类提供plus运算符的python方法。


If I have a string x='wow' in Python, I can concatenate this string with itself using the __add__ function, like so:

x='wow'  
x.__add__(x)  
'wowwow'

How can I do this in C++?

解决方案

Semantically, the equivalent of your python code would be something like

std::string x = "wow";
x + x;

i.e. create a temporary string which is the concatenation of x with x and throw away the result. To append to x you would do the following:

std::string x = "wow";
x += x;

Note the double quotes ". Unlike python, in C++, single quotes are for single characters, and double-quotes for null terminated string literals.

See this std::string reference.

By the way, in Python you wouldn't usually call the __add__() method. You would use the equivalent syntax to the first C++ example:

x = 'wow'
x + x

The __add__() method is just the python way of providing a "plus" operator for a class.

这篇关于简单字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆