String类的常用方法

 

String类的常用方法:

    public int length()  //返回字符串长度

  String s = "12345";
  System.out.println(s.length()); //5

    public boolean equals(Object anrObject)  //判断给定字符串与当前字符串比较, 如果两个字符串相等,则返回true, 否则返回false

String s1 = "12345";
String s2 = "54321";
System.out.println(s1.equals(s2)); // false
知识兔

    public String substring(int beginIndex)  //返回字符串从beginIndex开始的子串

String s = "12345";
System.out.println(s.substring(2)); //"345"
知识兔

  public String substring(int beginIndex, int endIndex)  //返回字符串从beginIndex开始到endIndex子串

String s = "12345";
System.out.println(s.substring(2,4)); //"34"
知识兔

    public char charAt(int index) //返回字符串中指定位置的字符;注意字符串中第一个字符索引是0,最后一个是length()-1

String s = "12345";
System.out.println(s.charAt(2)); //3
知识兔

    public int indexOf(String str) //返回str在字符串中第一次出现的位置

String s = "12345";
System.out.println(s.indexOf("34")); //2
知识兔

    public int compareTo(String anotherString) //若调用该方法的字符串大于参数字符串,则返回正整数,反之返回负整数,相等返回0

String s1 = "12345";
String s2 = "1234567";
System.out.println(s1.compareTo(s2)); //-2
知识兔

    public String replace(char oldChar, char newChar) //以newChar字符替代所有oldChar字符

String s = "12345";
System.out.println(s.replace('2', '6')); //16345
知识兔

    public String trim() //去掉字符串首尾空格

String s = "  1234 5  ";
System.out.println(s.trim()); //1234 5
知识兔

    public String toLowerCase()//将当前字符串中所有字符转换成小写字符并返回
    public String toUpperCase()//将当前字符串中所有字符转换成大写字符并返回

String s = "ABcd";
System.out.println(s.toLowerCase()); //abcd
System.out.println(s.toUpperCase()); //ABCD
知识兔

 

计算机