Replacing Substrings and Splitting Strings

Sometimes it’s useful to replace parts of a string or to split a string into pieces. For this purpose, class String provides methods replaceAll, replaceFirst and split. These methods are demonstrated in Fig. 14.23.

 1   // Fig. 14.23: RegexSubstitution.java 2   // String methods replaceFirst, replaceAll and split. 3   import java.util.Arrays; 4  5   public class RegexSubstitution 6   { 7      public static void main(String[] args) 8      { 9         String firstString = "This sentence ends in 5 stars *****";10         String secondString = "1, 2, 3, 4, 5, 6, 7, 8";11 12         System.out.printf("Original String 1: %s%n", firstString);13 14         // replace '*' with ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.