Java常用工具——java字符串

一、String常用字符串

package com.imooc.string;

public class StringDemo {
    public static void main(String[] args) {
        //定义一个字符串“JAVA 编程 基础”
        String str="JAVA 编程 基础";
        //打印输出字符串的长度
        System.out.println("字符串的长度是:"+str.length());
        //取出字符'程'并输出
        System.out.println(str.charAt(6));
        //取出子串"编程 基础"并输出
        System.out.println(str.substring(5));
        //取出子串"编程"并输出
        System.out.println(str.substring(5, 7));
    }

}
package com.imooc.string;

public class StringDemo2 {
    public static void main(String[] args) {
        //定义一个字符串“JAVA 编程 基础”
        String str="JAVA 编程 基础";
        //查找字符'A'在字符串中第一次出现的位置
        System.out.println("字符'A'在字符串中第一次出现的位置:"+str.indexOf('A'));
        //查找字符'A'在字符串中最后一次出现的位置
        System.out.println("字符'A'在字符串中最后一次出现的位置:"+str.lastIndexOf('A'));
        //查找子串"编程"在字符串中第一次出现的位置
        System.out.println("子串\"编程\"在字符串中第一次出现的位置:"+str.indexOf("编程"));
        //查找子串"编程"在字符串中最后一次出现的位置
        System.out.println("子串\"编程\"在字符串中最后一次出现的位置:"+str.lastIndexOf("编程"));
        //在字符串inde值为8的位置开始,查找子串"编程"在字符串中第一次出现的位置
        System.out.println("字符串inde值为8的位置开始,查找子串\"编程\"在字符串中第一次出现的位置:"+str.indexOf("编程", 8));
        
    }

}
package com.imooc.string;

import java.io.UnsupportedEncodingException;

public class StringDemo3 {

    public static void main(String[] args) throws UnsupportedEncodingException {
        // 字符串和byte数组之间的相互的转换
        //定义一个字符串
        String str=new String("JAVA 编程 基础");
        //1、将字符串转换为byte数组,并打印输出
        byte[] arrs=str.getBytes("GBK");
        for(int i=0;i<arrs.length;i++) {
            System.out.print(arrs[i]+" ");
        }
        System.out.println();
        //2、将byte数组转换为字符串
        String str1=new String(arrs,"GBK");
        System.out.println(str1);
    }

}
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/loveapple/p/11140098.html