早教吧 育儿知识 作业答案 考试题库 百科 知识分享

使用Java的String类操作字符串和子串。(1)声明一个String对象,其内容为“Iamastudent,Iamatccit”;(2)输出字符串的长度;(3)输出字符串的第一个和最后一个字符;(4)输出字符串的

题目详情
使用Java的String类操作字符串和子串。
(1)声明一个String对象,其内容为“I am a student,I am at ccit”;
(2)输出字符串的长度;
(3)输出字符串的第一个和最后一个字符;
(4)输出字符串的第一个和最后一个单词;
(5)将其中的‘c’替换为‘C’输出;
(6)输出其中的各个单词;
(7)判断字符串中是否包含“ma”这个单词;
(8)判断字符串是否以“I”开头,以“I”结尾。
编写JAVA程序:
▼优质解答
答案和解析
public class Du02 {
public static void main(String[] args) {
String str = "I am a student,I am at ccit";

System.out.println(str.length());

System.out.println(str.charAt(0));
System.out.println(str.charAt(str.length()-1));//

int firstIndex = str.indexOf(" ");
System.out.println("First word: " + str.substring(0, firstIndex));
int lastIndex = str.lastIndexOf(" ");
System.out.println("Last word: " + str.substring(lastIndex));

System.out.println(str.replace('c', 'C')); //

String[] ary = str.replace(",", " ").split("\\s+");
for(int i =0; i < ary.length; i++){
if(!ary[i].trim().equals("")){
System.out.println(ary[i].trim());
}
}

System.out.println("String contains ma? " + str.concat(" ma "));
System.out.println("String starts with 'i', ends with 'i'? " + str.matches("I(.)*I"));

}
}
-----------testing
27
I
t
First word: I
Last word: ccit
I am a student,I am at CCit
I
am
a
student
I
am
at
ccit
String contains ma? I am a student,I am at ccit ma
String starts with 'i', ends with 'i'? false