Java中String类的常用方法简介

String类的常用方法简介

  1. char cahrAt(int index)方法,使用charAt方法输入一个int index值即可返回索引值的字符.
		String s1 = "abcdefgh";
        System.out.println(s1.charAt(3));//输出:d
  1. int comepareTo(String anotherString)方法,按照字典顺序进行比较两个字符串。比较字符串时,从第一个字母开始比较,若一样则比较下一个字符。
		String s2 = "abc";
        String s3 = "abf";
        System.out.println(s2.compareTo(s3));//c-f=-3  输出-3
        String s2 = "abc";
        String s3 = "aff";
        System.out.println(s2.compareTo(s3));//b-f=-4  输出-4
  1. String concat(String str)方法,将指定字符串连接到此字符串的结尾.
		String s4 = "abc";
        String s5 = "def";
        System.out.println(s4.concat(s5));//输出:abcdef
  1. boolean contains(CharSequences s)方法,判断此字符串是否包含指定的字符串,如果是则返回为true否则返回false。
		String s4 = "abc";
        System.out.println(s4.contains("ab"));//输出:true
        System.out.println(s4.contains("e"));//输出:false
  1. boolean startsWith(String str)和boolean endWith(String str)方法,分别是判断字符串是否是以指定的字符串开始或结尾
		String s4 = "abc";
        System.out.println(s4.startsWith("ab"));//输出:true
        System.out.println(s4.endsWith("c"));//输出:true
  1. boolean isEmpty(),判断此字符串是否为空
 		String s5 = "";
        System.out.println(s5.isEmpty());//输出为:true
  1. byte[] getTypes()使用平台默认字符集将此String编码为byte序列,并将结果存储在一个新的byte数组中
		String s7 = "abcde";
        byte[] bytes = s7.getBytes();
        for (byte b:
             bytes) {
            System.out.println(b);
        }//输出97 98 99 100 101 
  1. int hashcode(),返回此字符串的哈希码
		String s7 = "abcde";
		System.out.println(s7.hashCode());//输出92599395
  1. int indexOf(int ch),返回指定字符在此字符串中第一次出现处的索引
    int indexOf(String str),返回指定子字符串在此字符串中第一次出现处的索引
		String s7 = "abcde";
		System.out.println(s7.indexOf(99));//输出2
        System.out.println(s7.indexOf("c"));//输出2
  1. int indexOf(int ch, int fromIndex),返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
    int indexOf(String str,int fromIndex),返回在此字符串中第一次出现指定子字符串的索引,从指定的索引开始搜索。
		String s8 = "abcdeabcde";
		System.out.println(s8.indexOf(100,4));//输出8
        System.out.println(s8.indexOf("d",4));//输出8
  1. int lenth(),返回字符串的长度
		String s8 = "abcdeabcde";
		System.out.println(s8.length());//输出10
  1. String replace(char oldChar,char new Char),返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的
 		String s9 = "abc";
        String s10 = "def";
        System.out.println(s9.replace("bc",s10));//输出adef
  1. char[] toCharArray(),将此字符串转换为一个新的字符数组
		String s10 = "def";
 		char[] chars = s10.toCharArray();
        for (char c :
                chars) {
            System.out.println(c);
        }//输出d e f
  1. String subString(int beginIndex),返回一个新的字符串,是此字符串的一个子字符串,返回的新的字符串包含头的开始部分
    String subString(int brginIndex,int endIndex),返回一个新的字串,是截取的此字符串的一个子字符串,返回的新的字符串包含头但是不包含尾
		String s11 = "abcdefgh";
        System.out.println(s11.substring(1));//输出bcdefgh
        System.out.println(s11.substring(1,3));//输出bc
发布了4 篇原创文章 · 获赞 15 · 访问量 409

猜你喜欢

转载自blog.csdn.net/qq_45920729/article/details/103897924