1.从控制台输入一段字符串,统计hello这个单词输入了多少次
public class test1 {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
//从控制台输入一段字符串,统计hello这个单词输入了多少次
//hellohellohellohello 4
System.out.println("请输入一段字符:");
String str=scanner.next();
int num=0;
int index=0;
char[] ch=str.toCharArray();
//如果该输入的字符串中含有hello
if (str.contains("hello")){
for (int i = 0; i < ch.length-4; i++) {
//如果第一个hello之后还能找到hello
if (str.indexOf("hello",index+4)!=-1) {
//次数加一次
num++;
index = str.indexOf("hello", index + 4);
}
}
}else {
num=0;
}
System.out.println("一共有"+(num+1)+"个hello");
}
}
public class test1 {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
//从控制台输入一段字符串,统计hello这个单词输入了多少次
//hellohellohellohello
System.out.println("请输入一段字符:");
String str=scanner.next();
String hello="hello";
int count=0;
for (int i = 0; i <str.length()-hello.length()+1; i++) {
if (str.substring(i,hello.length()+i).equals(hello)){
count++;
}
}
System.out.println("一共出现了"+count+"个hello");
}}
2. 给定一串字符串,四个数值分别是学生的姓名以及语文数学英语成绩
然后根据总成绩对学生的信息进行排名
public class test2 {
public static void main(String[] args) {
//给定一串字符串,四个数值分别是学生的姓名以及语文数学英语成绩
//根据总成绩对学生的信息进行排名
String str = "张三,55,66,77;李四,77,78,79;王五,89,88,87;赵六,78,88,99";
//对字符串进行拆分,得到每个学生的信息
String[] message1 = str.split(";");
Student[] students = new Student[message1.length];
for (int i = 0; i < message1.length; i++) {
//对每个学生的信息进行拆分,得到该学生的姓名和各科成绩
String[] message2 = message1[i].split(",");
Student student = new Student();
student.setName(message2[0]);
student.setChinese(Integer.parseInt(message2[1]));
student.setMath(Integer.parseInt(message2[2]));
student.setEnglish(Integer.parseInt(message2[3]));
student.setSum();
students[i] = student;
}
//根据学生总成绩对学生进行排序
for (int i = 0; i < students.length; i++) {
for (int j = 0; j < students.length - i - 1; j++) {
if (students[j + 1].getSum() >= students[j].getSum()) {
Student student = new Student();
student = students[j];
students[j] = students[j + 1];
students[j + 1] = student;
}
}
}
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}
}
}
3.找出里边的数字字符,转换为int后再相加求和
“asd1asd1fd1fd1”
public class test3 {
public static void main(String[] args) {
//找出里边的数字字符,转换为int后再相加求和
// “asd1asd1fd1fd1”
String str="asd4eq5wr1q1as5d1f1dd3fad1ff5eq7fd1";
char[] ch= str.toCharArray();
int sum=0;
for (int i = 0; i < ch.length; i++) {
//如果该字符是整数
if (Character.isDigit(ch[i])){
sum=sum+ch[i]-'0';
}
}
System.out.println(sum);
}
}
public class test3 {
public static void main(String[] args) {
String str = "asd4eq5wr1q1as5d1f1dd3fad1ff5eq7fd1";
int sum = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isDigit(ch)) {
sum=sum+Integer.parseInt(Character.toString(ch));
}
}}}