String 中 "+"的实现

本文深入探讨了Java中字符串(String)类型使用加号(+)进行拼接的具体实现方式。介绍了如何通过StringBuffer或StringBuilder类及其append方法来完成拼接过程,并解析了其背后的转换机制。

***String 中 "+"的实现

The Java language provides special support for the string concatenation operator ( + ), and for conversion

of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer)
class and its append method. String conversions are implemented through the method toString,defined
by Object and inherited by all classes in Java. For additional information on string concatenation and conversion,
see Gosling, Joy, and Steele, The Java Language Specification.
解释一下它这个api,String类型的对象使用“+”进行串连接的时候,是通过StringBuffer或者是StringBuilder的append()方法来实现的,这里可以做一个大胆的猜想:也就是说在执行“+”操作时String对象会将自身构造成StringBuffer或者StringBuilder对象,然后再通过他们的append()方法来实现,之后调用StringBuffer或者StringBuilder的toString()方法返回给表达式,在看看StringBuffer或者StringBuilder的toString()方法的源码:


参考文章:

1.关于java的String的探讨http://www.2cto.com/kf/201206/136505.html

2.JAVA中的String连接性能http://www.blogjava.net/javagrass/archive/2010/01/24/310650.html

3.JDK 1.5 String API http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html


好的,我理解你的要求是将两个字符串用等号连接起来赋值给另外一个字符串。我可以为你实现一个名为`operator=`的函数来达成这个目的: ```c++ #include <iostream> #include <string> using namespace std; int main() { string string1, string2 = "hello", string3 = "world"; string1 = string2 + " " + string3; cout << string1 << endl; // 输出 "hello world" return 0; } ``` 这个程序中,我们首先定义了三个字符串变量`string1`、`string2`和`string3`。然后,我们使用`+`运算符将`string2`和`string3`连接起来,中间用空格隔开。最后,我们将连接后的字符串赋值给`string1`。 如果你需要在你的程序中重载`operator=`函数来实现这个操作,你可以这样: ```c++ #include <iostream> #include <string> using namespace std; class MyString { private: string str; public: MyString() {} MyString(const string& s) : str(s) {} MyString operator=(const MyString& rhs) { str = rhs.str; return *this; } MyString operator=(const string& s) { str = s; return *this; } friend MyString operator+(const MyString& lhs, const MyString& rhs) { return MyString(lhs.str + rhs.str); } friend MyString operator+(const MyString& lhs, const string& rhs) { return MyString(lhs.str + rhs); } friend MyString operator+(const string& lhs, const MyString& rhs) { return MyString(lhs + rhs.str); } friend ostream& operator<<(ostream& os, const MyString& ms) { os << ms.str; return os; } }; int main() { MyString string1, string2 = "hello", string3 = "world"; string1 = string2 + " " + string3; cout << string1 << endl; // 输出 "hello world" return 0; } ``` 这个程序中,我们定义了一个名为`MyString`的类来表示字符串,重载了`operator=`函数和`operator+`函数。在`operator=`函数中,我们将右操作数的字符串赋值给左操作数的字符串,并返回左操作数的引用。在`operator+`函数中,我们将两个字符串连接起来,并返回一个新的`MyString`对象。最后,我们在`main`函数中使用这些运算符来实现你要求的操作,并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值