Java String substring

Introduction

String objects are immutable.

You can extract a substring using substring().

It has two forms.


String substring(int startIndex) 
String substring(int startIndex, int endIndex) 

The following program uses substring() to replace all instances of one substring with another within a string:

// Substring replacement.
public class Main {
  public static void main(String args[]) {
    String org = "This is a test from demo2s.com. This is, too.";
    String search = "is";
    String sub = "was";
    String result = "";
    int i;/* w ww .  ja v  a 2s  . c o  m*/

    do { // replace all matching substrings
      System.out.println(org);
      i = org.indexOf(search);
      if(i != -1) {
        result = org.substring(0, i);
        result = result + sub;
        result = result + org.substring(i + search.length());
        org = result;
      }
    } while(i != -1);

  }
}
public class Main {
   public static void main(String[] args) {
      String testString = "ABCDEFGHIJ";
      System.out.println(testString.substring(0));
      System.out.println(testString.substring(1));
      System.out.println(testString.substring(2));
      System.out.println(testString.substring(3));
      System.out.println(testString.substring(4));
      System.out.println(testString.substring(5));
      System.out.println(testString.substring(6));
      System.out.println(testString.substring(7));
      System.out.println(testString.substring(8));
      System.out.println(testString.substring(9));
   }/*ww w.  j  av  a2  s  .  c o m*/
}
substring(int beginIndex, int endIndex) 
public class Main{  
   public static void main(String[] args) {
      String testString = "ABCDEFGHIJ";
      System.out.println(testString.substring(0,5));
      System.out.println(testString.substring(1,5));
      System.out.println(testString.substring(2,5));
      System.out.println(testString.substring(4,5));
      /*from ww w  . j  av a  2s . c  o m*/
      System.out.println(testString.substring(0,6));
      System.out.println(testString.substring(1,6));
      System.out.println(testString.substring(2,6));
      
      System.out.println(testString.substring(0,7));
      System.out.println(testString.substring(1,7));
      System.out.println(testString.substring(2,7));
   }
}



PreviousNext

Related