java string截取前幾位 java截取最后一位字符



文章插圖
java string截取前幾位 java截取最后一位字符

文章插圖

字符串是引用類型,但是為什么不用new,因為太常用了,就簡化了 。
如果你不覺得煩,也能寫成:
String name = new String("name");String name = "name"; //就行了既然是個對象就有屬性和方法:
它的方法無非就是幫助我們方便的處理這個字符串 。
【java string截取前幾位 java截取最后一位字符】注:使用string一定要注意,必須用一個新的String接受 。
String substring = name.substring(1, 3);(1)符串查找
String 類的 indexOf() 方法在字符串中查找子字符串出現的位置,如果存在返回字符串出現的位置(第一位為0),如果不存在返回 -1 。
public class SearchStringEmp {public static void main(String[] args) {String strOrig = "xinzhi bigdata Java";int intIndex = strOrig.indexOf("Java");if(intIndex == - 1){System.out.println("沒有找到字符串 Java");}else{System.out.println("Java 字符串位置 " + intIndex);}}}也可以用contains() 方法
(2)字符串替換
java String 類的replace 方法可以替換字符串中的字符 。
public class test {public static void main(String args[]){ String str="Hello World,Hello Java." ;System.out.println(str.replace('H','W')); //替換全部System.out.println(str.replaceFirst("He","Wa")); // 替換第一個遇到的System.out.println(str.replaceAll("He", "Ha")); //替換全部}}
java程序員必備的基礎知識_java面向對象之String關鍵字
(3)字符串分割
split(string) 方法通過指定分隔符將字符串分割為數組 。
public class test {public static void main(String args[]){ String str="www-baidu-com";String delimeter = "-"; //指定分隔符 String[] temp = str.split(delimeter);//分割字符串//普通for循環for(int i =0; i < temp.length; i++){System.out.println(temp[i]);System.out.println("");}System.out.println("----java for each循 環輸出的方法-----");String str1 = "www.baidu.com";String delimeter1 = "\\."; //指定分隔符,.號需要轉義,不會明天講String[] temp1 = str1.split(delimeter1);for (String x : temp1){System.out.println(x);System.out.println("");}}}(4)字符串截串
substring(string) 方法可以截取從第幾個下標(0開始,包含第一個 開始)到第幾個下標(不包含)的字符串 。
public class test {public static void main(String args[]){name = new String("name");substring = name.substring(1, 3);}}(5)字符串小寫轉大寫
String toUpperCase() 方法將字符串從小寫轉為大寫 。
作業:
查找某個單詞在文章中出現的次數:
public static void main(String[] args) {String str = "Hello World abc Hello";// 截取字符串 第一個包含的 第二個不包含Test2 test2 = new Test2();int count = test2.wordCount(str, "HeLlo");System.out.println(count);}public int wordCount(String article, String word){//1、先把文章打散成數組String[] words = article.split(" ");int res = 0;for (int i = 0; i < words.length; i++) {if(words[i].equalsIgnoreCase(word)){res++;}}return res;}