java 字符串 复制_Java字符串复制

java 字符串 复制

Sometime back I was asked how to copy a String in java. As we know that String is an immutable object, so we can just assign one string to another for copying it. If the original string value will change, it will not change the value of new String because of immutability.

有时,我被问到如何在Java中复制字符串。 我们知道String是一个不可变的对象,因此我们可以将一个字符串分配给另一个字符串以进行复制。 如果原始字符串值将更改,则由于不变性,它将不会更改新String的值。

Java字符串复制 (Java String Copy)

Here is a short java String copy program to show this behavior.

这是一个简短的Java String复制程序,用于显示此行为。

package com.journaldev.string;

public class JavaStringCopy {

	public static void main(String args[]) {
		String str = "abc";

		String strCopy = str;

		str = "def";
		System.out.println(strCopy); // prints "abc"

	}
}

Note that we can perform direct assignment of one variable to another for any immutable object. It’s not limited to just String objects.

请注意,对于任何不可变的对象,我们都可以将一个变量直接分配给另一个变量。 它不仅限于String对象。

However, if you want to copy a mutable object to another variable, you should perform deep copy.

但是,如果要将可变对象复制到另一个变量,则应执行Deep copy

Java字符串复制备用方法 (Java String Copy Alternate Methods)

There are few functions too that can be used to copy string. However it’s not practical to use them when you can safely copy string using assignment operator.

也很少有功能可用于复制字符串。 但是,当您可以使用赋值运算符安全地复制字符串时,使用它们并不实际。

  1. Using String.valueOf() method
    String strCopy = String.valueOf(str);
    
    String strCopy1 = String.valueOf(str.toCharArray(), 0, str.length()); //overkill*2

    使用String.valueOf()方法
  2. Using String.copyValueOf() method, a total overkill but you can do it.
    String strCopy = String.copyValueOf(str.toCharArray());
    
    String strCopy1 = String.copyValueOf(str.toCharArray(), 0, str.length()); //overkill*2

    使用String.copyValueOf()方法,完全可以解决问题,但是您可以做到。
valueOf and valueOfcopyValueOf methods are useful. copyValueOf方法很有用。

翻译自: https://www.journaldev.com/20811/java-string-copy

java 字符串 复制

  • 10
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值