本文涉及知识: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]);
}
}

本文深入探讨Java中String类的多种实用方法,包括substring()用于字符串截取,indexOf()和lastIndexOf()进行字符串定位,charAt()获取指定位置字符,replace()实现字符串替换,contains()检查子串是否存在,以及split()将字符串分割为数组。通过具体示例,展示如何运用这些方法解决实际编程问题。
1万+

被折叠的 条评论
为什么被折叠?



