开发中涉及到大量的对String的处理,熟练掌握String的常用方法,可以提高开发效率。
1. 字符与字符串,常用的方法有:
- public String(char[] value)
- public String(char[] value, int offset, int count)
- public char charAt(int index)
- public char[] toCharArray()
{ //public char charAt(int index) //取出指定索引的字符 String str = "hello"; char c = str.charAt(1); System.out.println(c); } { //public char[] toCharArray() //字符数组与字符串的转换 String str = "hello"; char[] strInCharArray = str.toCharArray(); for(char item : strInCharArray) { System.out.print(item + " "); } System.out.println(); } { //public char[] toCharArray() //判断一个给定的字符串是否有数字组成 String str = "13212A355565"; char[] strInCharArray = str.toCharArray(); boolean flag = true; for(char item : strInCharArray) { if(item < '0' || item > '9') { flag = false; break; } } System.out.print(str + ": "); if(flag) { System.out.println("全部由数字组成!"); } else { System.out.println("不是全由数字组成!"); } }
2. 字节与字符串
- String(byte[] bytes)
- String(byte[] bytes, int offset, int length)
- public byte[] getBytes()
- public byte[] getBytes(Charset charset)
//public byte[] getBytes() //字符串与字节数组的转换 String str = "hello world"; byte[] strInBytes = str.getBytes(); for(byte item : strInBytes) { System.out.println((int)item); }
3. 字符串比较
- public boolean equals(Object anObject)
- public boolean equalsIgnoreCase(String anotherString)
String str1 = "hello"; String str2 = "HELLO"; System.out.println(str1.equals(str2));//false System.out.println(str1.equalsIgnoreCase(str2));//true
4. 字符串查找
- public boolean contains(CharSequence s)
- public int indexOf(String str)
- public int indexOf(String str, int fromIndex)
- public int lastIndexOf(String str)
- public int lastIndexOf(String str, int fromIndex)
- boolean startsWith(String prefix)
- public boolean startsWith(String prefix, int toffset)
- public boolean endsWith(String suffix)
String str = "hello world"; System.out.println(str.indexOf("world")); System.out.println(str.indexOf("l")); System.out.println(str.indexOf("l",5)); System.out.println(str.lastIndexOf("l"));
5. 字符串替换
- public String replaceAll(String regex, String replacement)
- public String replaceFirst(String regex, String replacement)
String str = "hello world"; String resultA = str.replaceAll("l", "*"); String resultB = str.replaceFirst("l", "*"); System.out.println(str); System.out.println(resultA); System.out.println(resultB);
6. 字符串截取
- public String substring(int beginIndex)
- public String substring(int beginIndex,int endIndex)
String str="hello world"; String resultA = str.substring(6); String resultB = str.substring(2, 4); System.out.println(resultA); System.out.println(resultB);
7. 字符串拆分
- public String[] split(String regex)
- public String[] split(String regex, int limit)
String str="192.168.1.1"; String[] results = str.split("\."); for(String item : results) { System.out.print(item+" "); }
8. 其它常用方法
- public String toLowerCase()
- public String toUpperCase()
- public String trim()
- public String concat(String str)
- public int length()
- public boolean isEmpty()