String(Java版本)

import java.io.UnsupportedEncodingException;

public class Driver {
    public static void main(String[] args) {
        String motto = "Nothing is equal to knowledge 知识就是万能钥匙";
        System.out.println(motto);
        System.out.println("格言字符串的长度:	" + motto.length());// 求长度  注意包含空格
        System.out.println(motto.indexOf('q'));//求所在字符下标
        System.out.println(motto.charAt(12));//取出q 并打印输出
        System.out.println(motto.indexOf('k'));//求所在字符下标
        System.out.println(motto.substring(11));//求子串
        System.out.println(motto.substring(20));//求子串
        System.out.println(motto.substring(11, 16));//区间取字符串  左闭右开[)
        System.out.println(motto.indexOf('i')); //求出第一次出现字符的位置
        System.out.println(motto.indexOf("to", 5)); //从第五个位置开始  求出第一次出现字符的位置

        System.out.println(motto.indexOf("equal"));// 字符串第一次出现的位置

        System.out.println(motto.lastIndexOf("to"));//最后一次出现的字符串
        System.out.println(motto.lastIndexOf('k'));//最后一次出现的字符


        // 不推荐使用这种方式打印字符串
        for (int i = 0; i < motto.length(); i++) {
            System.out.print(motto.charAt(i));
        }
        System.out.println();
/**
 * 主要用于网络传输
 */
//        byte[] bytes = motto.getBytes();//UTF-8模式
        byte[] bytes = new byte[0];
        try {
            bytes = motto.getBytes("GBK");//GBK-8模式
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i] + "	"); //二进制数据
        }

        System.out.println();
//        将byte数组转为字符串
        //方法1
//        String string = new String(bytes); //UTF-8模式
        String string = null;
        try {
            string = new String(bytes, "GBK");//GBK-8模式
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(string);
//        方法2
        try {
            System.out.println(new String(bytes, "GBK"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

/**
 * 判断内容是否相同
 */
        String name01 = "wanson";
        String name02 = "wanson";
        String name03 = new String("wanson");


        System.out.println(name01.equals(name02));
        System.out.println(name01.equals(name03));
        /**
         * 地址是否相同
         */
        //栈存放引用
        //堆存放new 对象
        //常量池  存放内容
        System.out.println(name01==name02);
        System.out.println(name01==name03);

    }
}

原文地址:https://www.cnblogs.com/wanson/p/10667850.html