String类型需要注意的几个问题

String类型属于不可变类型(不可变类型是指该类型创建了一个实例后,就不允许修改该实例的值),在学习和使用的时候需要注意一下几个问题

1.new String("abc");执行这个操作后,整个程序中有几个"abc"对象?

解析:这个操作创建了1个或者2个对象,如果常量池中原来有"abc"(也就是说在执行此操作之前已经创建了一个字符串"abc",已经把它存到常量池中,再次创建会自动从常量池中取出,而不会再创建新的"abc"字符串),那么整个程序就只创建了一个对象;如果在执行该操作之前,常量池中没有字符串"abc",那么就会创建2个对象,其中一个要存于常量池中,另一个存于堆内存中。

2.以下代码

String s = "abc";
String ss = "ab" +"c";
System.out.println(s==ss);

输出结果为true,String ss ="ab"+"c";这步操作在编译器就已经能确定ss="abc",ss对象在创建的时候直接取常量池中的s对象,所以ss和s是同一个对象。

3.以下代码

String s = "abc";
char[] ch ={'a','b','c'};
System.out.println(s.equals(ch));

输出结果为false,因为s和ch分别为字符创类型和数组类型,两者进行equals必然为false。

4.如下代码

public static void changeStringBuffer(StringBuffer ss1,StringBuffer ss2){
   ss1.apend("World");
   ss2 = ss1;

}

public static void main(String[] args){
   StringBuffer s1 = new StringBuffer("Hello");
   StringBuffer s2 = new StringBuffer("Hello");
   changeStringBuffer(s1,s2);
   System.out.println(s1);
   System.out.println(s2);
}

输出结果为:

Hello World

Hello

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C++ 中,string 类型是一个非常常用的字符串类,可以方便地进行字符串的操作。使用 string 类型需要注意以下几点: 1. 头文件:需要包含 <string> 头文件。 2. 声明:需要使用 std 命名空间,或者在全局范围内使用 using namespace std; 声明。 3. 初始化:可以直接使用字符串字面量或者其他 string 对象初始化。 4. 操作:可以使用常规的字符串操作,如比较、拼接、查找、替换等。 5. 长度:可以使用 size() 或者 length() 方法获取字符串的长度。 6. 遍历:可以使用 for 循环或者迭代器遍历字符串中的每一个字符。 7. 转换:可以使用 c_str() 方法将 string 类型转换为 const char* 类型,或者使用 stoi()、stof() 等方法将 string 类型转换为其他类型。 示例代码: ``` #include <iostream> #include <string> using namespace std; int main() { string s1 = "hello"; string s2("world"); string s3 = s1 + " " + s2; cout << s3 << endl; if (s1 == "hello") { cout << "s1 equals to hello" << endl; } int index = s3.find("world"); if (index != string::npos) { cout << "world found at index " << index << endl; } for (char c : s3) { cout << c << " "; } cout << endl; const char* cstr = s3.c_str(); cout << "cstr: " << cstr << endl; return 0; } ``` 输出结果: ``` hello world s1 equals to hello world found at index 6 h e l l o w o r l d cstr: hello world ``` 需要注意的是,string 类型的底层实现是动态分配的内存,因此在进行大量字符串操作时需要注意内存的使用。同时,由于 string 对象的复制和传递会涉及到内存的拷贝,因此也需要注意效率问题

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值