String和字符数组互转

一、String转字符数组:

1.用toCharArray()方法。

        String text = "to be or not to be";
        char[] textArray = text.toCharArray();
        System.out.println(textArray);

 2.还可以用getChars方法,四个参数对应的说明是

  • srcBegin -- 字符串中要复制的第一个字符的索引。

  • srcEnd -- 字符串中要复制的最后一个字符之后的索引。

  • dst -- 目标数组。

  • dstBegin -- 目标数组中的起始偏移

        String text = "to be or not to be";
        char[] textArray = new char[3];
        text.getChars(9,12,textArray,0);
        System.out.println(textArray);
扫描二维码关注公众号,回复: 429938 查看本文章

二、字符数组转String

1.用String.copyValueOf方法。

两种声明方法:

1.public static copyValueOf(char[] data)

2.public static copyValueOf(char[] data,int offset,int count)

offset:子数组的初始偏移量;count:子数组的长度

        String text = "to be or not to be";
        char[] textArray = text.toCharArray();
        System.out.println(textArray);

        String text1 = String.copyValueOf(textArray);
        String text2 = String.copyValueOf(textArray,9,3);
        System.out.println(text1);
        System.out.println(text2);

  

2.String类的构造函数,与上面的结果一样

        String text = "to be or not to be";
        char[] textArray = text.toCharArray();
        System.out.println(textArray);

        String text1 = new String(textArray);
        String text2 = new String(textArray,9,3);
        System.out.println(text1);
        System.out.println(text2);

猜你喜欢

转载自z1414644039.iteye.com/blog/2414907