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