java basics: 9, commonly used method of the String class what?

Common methods of the String class have?

String class is a string type, final modified type, underlying character array is immutable.

Acquisition method

		String str = new String("123456789");
		
		/**
		 * 获取信息
		 */
		System.out.println(""+str.length());//9,获取字符串长度
		System.out.println(""+str.indexOf("2"));//1,获取指定字符在字符串中的位置
		System.out.println(""+str.lastIndexOf("1"));//0,获取指定字符在字符串中最后一次出现的位置
		System.out.println(""+str.charAt(3));//4,获取指定索引处的字符
		

Interception / Split string

/**
		 * 截取字符串
		 */
		System.out.println(""+str.substring(5));//6789,从指定索引处截取字符串
		System.out.println(""+str.substring(5,7));//67,从指定索引处截取字符串
		 /**
		  * 按照指定字符分割字符串
		  */
		 String[] chaStr=str3.split("9");

Judging method

		/**
		 * 判断方法
		 */
		String str1 = new String("12345678AABn9");
		System.out.println(""+str1.equalsIgnoreCase("12345678aaBn9"));//true;判断字符串内容是否相等,忽略大小写
		System.out.println(""+str1.equals("123"));//false;判断字符串内容是否相等
		System.out.println(""+str1.startsWith("123"));//true;判断字符串是否以123开始
		System.out.println(""+str1.endsWith("123"));//false;判断字符串是否以123结束

Conversion process

/**
		  * 转化方法
		  */
		 char[] strChar=str1.toCharArray();//转化为字符数组
		 System.out.println(""+str1.toLowerCase());//全部转化为小写
		 System.out.println(""+str1.toUpperCase());//全部转化为大写

Remove trailing spaces

		 /**
		  * 去掉首尾两端空格
		  */
		 String str3=" 19898kjsd 09djkkkkkkj  ";
		 System.out.println(str3.trim());//去掉首尾两端空格

Construction method

    //封装空字符串对象
    public String() {
        this.value = "".value;
    }
    //将字符串数据封装成字符串对象
    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
    //将字符串数组转换成字符串
    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }   
    //将字符数组的指定位置后的一定长度转换成字符串
  public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= value.length) {
                this.value = "".value;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }
 

Published 56 original articles · won praise 13 · views 1197

Guess you like

Origin blog.csdn.net/weixin_42924812/article/details/105053342