String 类的选择输出

package com.day_08.strings;

/*
 * 通过API可知/String是在Java.lang包下的类,所以不用导包
 */
public class StringDemo {
    public static void main(String[] args) {
今天幸亏我比较机智想到了这个问题,要不然就只跟着例子跑偏了.代码中的方法三,对我来说有点绕,在写这篇文章的时候看到了count ,才发现是计数不是最后的位置索引.汗....
但没关系,写出来能让我记忆更深刻倒是没毛病.
//方式一:String (String original);把字符串数据封装成字符串对象 String s = new String("hello"); System.out.println(s); System.out.println("-----------"); //方式二:String(char[] value);把字符数组的数据封装成字符串对象 //此类方法在做特殊输出是用的到 char[] arr = {'a','b','c','h','e','l','l','o'}; String s1 = new String(arr); System.out.println(s1); System.out.println("-----------"); //方式三:String(char[] value , int index ,int count):把字符数组中的一部分数据封装成字符对象[index---到-(index+count-1)] //此类方法在做特殊输出是用的到 String s2 = new String (arr,1,4);//注意:1:是开始的索引,4:是从1开始向后数四个位置,即输出是bche System.out.println(s2); System.out.println("-----------"); //方法四:直接赋值 String s4 = "abcdefgh"; System.out.println(s4); } }
原文地址:https://www.cnblogs.com/lkyang/p/7729557.html