一、实现方法 contains, 能够判定字符串中是否包含子串
public class Test5 {
public static void main(String[] args) {
String str = "helloword";
System.out.println(str.contains("hello"));
System.out.println(str.contains("helow"));
}
}
二、实现方法 indexOf, 能够找出字符串子串存在的位置
public class Test4 {
public static void main(String[] args) {
String str = "hello word";
System.out.println(str.indexOf("ell"));
System.out.println(str.indexOf("or", 2));
System.out.println(str.indexOf("oll"));
}
}
三、java实现一个方法 sum, 以数组为参数, 求数组所有元素之和
public class Test3 {
public static void main(String[] args) {
int[] arr={1,2,3};
int ret=sum(arr);
System.out.println(ret);
}
public static int sum(int[] a){
int ret2=0;
for(int x:a){
ret2+=x;
}
return ret2;
}
}
四、实现方法 replace, 能够替换字符串中的某个部分
public class Test2 {
public static void main(String[] args) {
String str = "hello word";
System.out.println(str.replaceAll("l","-"));
System.out.println(str.replaceFirst("l","-"));
}
}
五、实现方法 compareTo, 能够实现按照字典序比较字符串大小
public class Test1 {
public static void main(String[] args) {
String str1 = "ac";
String str2 = "AA";
System.out.println("AA".compareTo(str2));
System.out.println(str1.compareTo(str2));
System.out.println(str2.compareTo(str1));
}
}