代码演示
* @Description//字符串常用提取方法:
*/
public class StrMethods {
public static void main(String[] args) {
// //获取字符串中特定字符串的位置
// String s="hello world!";
// //indexOf:查找某个特定字符串在整个字符串中第一次出现的位置
// //字符串下标从0开始
// int index=s.indexOf("o");
// System.out.println(index);
// //查找不到位置,返回-1
// int index2=s.indexOf("yes");
// System.out.println(index2);
// //lastIndexOf:查找某个特定字符串在整个字符串中最后一次出现的位置
// int index3=s.lastIndexOf("o");
// System.out.println(index3);
//
// //截取特定字符串内容
// //substring(index):从index位置(包含)开始截取,一直截取到字符串末尾
// String result=s.substring(4);
// System.out.println(result);
//
// //substring(index1,index2):从index1位置(包含)开始截取,截取到index2位置(不包含)的
字符串
// String result2=s.substring(4,8);
// System.out.println(result2);
//截取"小鱼儿"
String word = "Hello, ";
word = word.trim();
String s = word.concat("小鱼儿!");
int index1 = s.indexOf(',');
int index2 = s.indexOf('!');
System.out.println(s.substring(index1+1, index2));
}
}
练习:
代码演示
* @Description//作业提交验证
* //作业后缀名正确.java 邮箱格式正确@.
*/
public class JobSubmit {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("********欢迎进入作业提交系统******");
System.out.println("请输入您要提交的文件名");
String fileName=input.next();
System.out.println("请输入您的个人邮箱");
String email=input.next();
boolean jobFlag=false;//作业后缀名是否正确,正确true,反之false
boolean emailFlag=false;//邮箱名是否正确,正确true,反之false
//作业后缀名是否正确
int index=fileName.lastIndexOf(".");
if (index!=-1&&fileName.substring(index).equals(".java")){
jobFlag=true;
}else {
System.out.println("文件名无效!请重新提交!");
}
//邮箱名是否正确
int index2=email.lastIndexOf("@");
int index3=email.lastIndexOf(".");
if (index2!=-1&&index3!=-1&&index2<index3) {
emailFlag = true;
}else {
System.out.println("邮箱名无效!请重新提交!");
}
//作业是否提交成功的提示
if (jobFlag&&emailFlag){
System.out.println("作业提交成功!");
}else {
System.out.println("作业提交失败!");
}
}
}
字符串提取时注意
重载方法的作用不同
方法的参数含义
字符串下标从0开始
代码演示
public class Counter {
//查找某个特定字符串在整个字符串中出现的次数
public int counter(String info,String find){
int count=0;
String[] chars=new String[info.length()];
//字符串转换为数组元素
for (int i = 0; i < chars.length; i++) {
chars[i]=info.substring(i,i+1);//把字符串info中i位置的字符串依次取出,放入字符串数组chars中
if (chars[i].equals(find)){
count++;
}
}
return count;
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入一个字符串:");
String info=input.next();
System.out.println("请输入您要查找的字符:");
String find=input.next();
Counter c=new Counter();
int count=c.counter(info,find);
System.out.println("\""+info+"\""+"中包含了"+count+"个"+"\""+find+"\"");
}
}
字符串拆分方法
代码演示
* @Description//字符串拆分方法:
*/
public class StrMethods {
public static void main(String[] args) {
System.out.println("*********原歌词********");
String song="长亭外 古道边 芳草碧连天 晚风拂柳笛声残 夕阳山外山";
System.out.println(song);
//把字符串拆分-->String[]
String[] songs=song.split(" ");//引号里是一个空格
System.out.println("********拆分后歌词********");
for (String s:songs){
System.out.println(s);
}
}
}