Java初步學習——2021.10.09每日總結,第五週週六
阿新 • • 發佈:2021-10-10
(1)今天做了什麼; (2)明天準備做什麼? (3)遇到的問題,如何解決?
今天學習了菜鳥教程例項部分
一、字串
1.字串比較——compareTo方法
public class Main { public static void main(String[] args) { String str = "Hello World"; String anotherString = "hello world"; Object objStr = str; System.out.println(str.compareTo(anotherString)); System.out.println(str.compareToIgnoreCase(anotherString));//忽略大小寫 System.out.println(str.compareTo(objStr.toString())); } }
2.字串最後出現的位置——lastIndexOf方法
//字串最後一次出現的位置 public class Main { public static void main(String[] args) { String strOrig = "Hello world,Hello Runoob"; int lastIndex = strOrig.lastIndexOf("Runoob"); if(lastIndex == -1) { System.out.println("沒有找到字串 Runoob"); } else { System.out.println("Runoob 字串最後出現的位置: " + lastIndex); } } }
3.substring函式的使用,以及刪除字串中的一個字元
//刪除字串中的一個字元 public class Main { public static void main(String[] args) { String str = "this is java"; str = removeCharAt(str,4); System.out.println(str); } public static String removeCharAt(String string,int num) { //substring(x,y) :擷取從下標為x的字元開始,到下標y-1的字元結束 substring(x):擷取從下標為x的字元到字串末尾的字串 string = string.substring(0, num) + string.substring(num + 1); return string; } }
4.字串替換——replace方法
public class Main { public static void main(String[] args) { String str = "Hello World"; System.out.println(str.replace('H','W')); System.out.println(str.replace("He", "Wa")); System.out.println(str.replace("He", "Ha")); } }
明天繼續字串例項。
今天沒有遇到什麼問題。