本文涉及知识:String类:substring() replace() contain() split() indexof() lastindexof() charAt()
可实现:截取固定字符串、串内查找目标字符串、字符串替换、字符串分割 放入字符串数组、字符串判断
1.直接截取substring()方法
public class Test {
public static void main(String[] args) {
String num="201706060318";
String temp=num.substring(4,6);
System.out.print(temp);
getInfoByNum(temp);
}
public static void getInfoByNum(String temp)
{
switch (temp){
case "01":System.out.println("轻工学院");break;
case "02":System.out.println("材料学院");break;
case "03":System.out.println("环境学院");break;
case "04":System.out.println("食品学院");break;
case "05":System.out.println("机电学院");break;
case "06":System.out.println("电控学院");break;
case "07":System.out.println("电智学院");break;
}
}
}
2.索引法: indexof() lastindexof() charAt()
public class test1 {
public static void main(String[] args) {
//截取某些特定字符串
String str="1234567389";
System.out.println(str.indexOf('3'));
System.out.println(str.lastIndexOf('3'));
String str1="201706060101";
char ch1=str1.charAt(4);
char ch2=str1.charAt(5);
System.out.println(ch1+""+ch2);
}
}
3.字符串替换,判断 replace() 和 contain()
//检验字符串是否有特定字符穿
String str3="天边 有 佳人 ,代 码打得好";
System.out.println(str3.replaceAll(" ", "").contains("代码"));
String str4="123@qq.com";
System.out.println(str4.contains("@"));
System.out.println(str4.indexOf('@')>=0);
4.字符串分割 split()
public class StringTest3 {
public static void main(String[] args)
{
userInfoDeal("tom,123456,35456789,123456@126.com");
}
public static void userInfoDeal(String userInfo)
{
//分割字符串放入字符串数组
String[] strs=userInfo.split(",");
System.out.println("name:"+strs[0]);
System.out.println("number:"+strs[1]);
System.out.println("QQ:"+strs[2]);
System.out.println("email:"+strs[3]);
}
}