String类常用的方法

66 阅读1分钟

image.png

image.png

// 测试字符串
public class TestString {
    public static void main(String[] args) {
        String s1 = "core Java";
        String s2 = "Core Java";
        System.out.println(s1.charAt(3)); // e
        System.out.println(s2.length()); // 9
        System.out.println(s1.equals(s2)); // false
        System.out.println(s1.equalsIgnoreCase(s2)); // true
        System.out.println(s1.indexOf("Java")); // 5
        System.out.println(s1.indexOf("apple")); // -1
        String s = s1.replace(" ", "&"); 
        System.out.println(s);// core&Java
    }
}
// 测试字符串
public class TestString {
    public static void main(String[] args) {
        String s = "";
        String s1 = "How are you?";
        System.out.println(s1.startsWith("How")); // true
        System.out.println(s1.endsWith("you")); // false
        s = s1.substring(4);
        System.out.println(s); // are you?
        s = s1.substring(4, 7);
        System.out.println(s); // are
        System.out.println(s1.toLowerCase()); // how are you?
        System.out.println(s1.toUpperCase()); // HOW ARE YOU?
        String s2 = " how old are you";
        s = s2.trim();
        System.out.println(s); // how old are you
        System.out.println(s2); // " how old are you";
    }
}

字符串是否相等的判断

  • equals方法用来检测两个字符串内容是否相等。如果字符串s和t内容相等,则s.equals(t)返回true,否则返回false。
  • 要测试两个字符串除了大小写区别外是否是相等的,需要使用equalsIgnoreCase()方法。
  • 判断字符串是否相等不要使用"=="。