字符串由来
通过以下编码可以看出,字符串实际就是字符数组。
char chars[]={'a','b','c'}; String s=new String(chars); System.out.println(s); int len=s.length(); System.out.println(len);
字符串转成byte数组
String s = "Hello world"; byte[] bytes = s.getBytes(); for (byte b : bytes) { System.out.print((char)b); }
常用字符串函数列表:
length()//取得字符串的长度
substring()//字符串截取
concat() //连接两个字符串
replace()//替换
trim()//去掉起始和结尾的空格
valueOf()//转换为字符串
toLowerCase()//转换为小写
toUpperCase()//转换为大写
toCharArray()//转char数组
equals()//比较两个字符串区分大小写
equalsIgnoreCase()//比较两个字符串不区分大小写
indexOf()//查找字符或者子串第一次出现的地方
lastIndexOf()//查找字符或者子串是后一次出现的地方
split()//字符串分割
substring
package Action; public class demo { public static void main(String[] args) { String str="I HAVE A DREAM!"; String s = str.substring(2, 2+4); System.out.println(s); } }
replace
package Action; public class demo { public static void main(String[] args) { String str="I HAVE A DREAM!"; String s = str.replace("DREAM", "GOOD IDEA"); System.out.println(s); } }
trim
package Action; public class demo { public static void main(String[] args) { String str="\tI HAVE A DREAM!\t"; String s = str.trim(); System.out.println(s); } }
toCharArray
package Action; public class demo { public static void main(String[] args) { String str = "89dsa dady8)ILuhd9usa)(*YGIUhdusa hoi"; char[] array = str.toCharArray(); int low = 0; int up = 0; int num = 0; int other = 0; for (char c : array) { if (c >= 'a' && c <= 'z') { low++; } else if (c >= 'A' && c <= 'Z') { up++; } else if (c >= '0' && c <= '9') { num++; } else { other++; } } System.out.println(str.length()); System.out.println(low); System.out.println(up); System.out.println(num); System.out.println(other); } }
toLowerCase与toUpperCase
package Action; public class demo { public static void main(String[] args) { String str="I HAVE A DREAM!"; String lowerCase = str.toLowerCase(); System.out.println(lowerCase); String upperCase = str.toUpperCase(); System.out.println(upperCase); } }
indexOf
package Action; import java.util.UUID; public class demo { public static void main(String[] args) { String str = UUID.randomUUID().toString().replaceAll("-", ""); String fileName = str.concat(".jpg"); int indexOf = fileName.indexOf(".jpg"); System.out.println(indexOf); System.out.println(fileName.substring(indexOf,fileName.length())); } }
split
package Action; import java.util.UUID; public class demo { public static void main(String[] args) { String str = UUID.randomUUID().toString(); System.out.println(str); String[] split = str.split("-",str.length()); for (String string : split) { System.out.println(string); } } }