集册 Java实例教程 字符串方法replaceFirst,replaceAll和split。

字符串方法replaceFirst,replaceAll和split。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

585
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
字符串方法replaceFirst,replaceAll和split。
import java.util.Arrays;
/*n o w j a v a . c o m - 时  代  Java 提供*/

public class Main

{

   public static void main(String[] args)

   {

      String firstString = "This sentence ends in 5 stars *****";

      String secondString = "1, 2, 3, 4, 5, 6, 7, 8";

         

      System.out.printf("Original String 1: %s\n", firstString);


      // replace '*' with '^'

      firstString = firstString.replaceAll("\\*", "^");
      /*
      nowjava.com - 时代Java 提供
      */


      System.out.printf("^ substituted for *: %s\n", firstString);


      // replace 'stars' with 'carets'

      firstString = firstString.replaceAll("stars", "carets");


      System.out.printf(

         "\"carets\" substituted for \"stars\": %s\n", firstString);


      // replace words with 'word'

      System.out.printf("Every word replaced by \"word\": %s\n\n",

         firstString.replaceAll("\\w+", "word"));


      System.out.printf("Original String 2: %s\n", secondString);


      // replace first three digits with 'digit'     

      for (int i = 0; i < 3; i++)

         secondString = secondString.replaceFirst("\\d", "digit");


      System.out.printf(

         
展开阅读全文