Java                                                          Home : www.sharetechnote.com

 

 

 

 

Java - String

 

When Java first came out and not so many other languages were there, one of the most attractive feature of Java was its powerful capability of String manipulation. In my personal experience as well, the String manipulation capability in Java was so attractive comparing to C language that I mainly used at the time. Now we have other languages like Python, Visual Basic, C# etc with similar capabilities. But still the strong String manipulation capability would be regarded as one of the strongest feature of Java.

 

As in other pages, I wouldn't describe each of the String manipulation methods one by one like a dictionary. You can easily find a lot of dictionary style documents and tutorials from internet. So I don't want to put another dictionary on top of them.  I would just show you some of examples under several topics / questions that would arise when you are trying to write any program that requires various string manipulation.

 

 

 

 

How to Create a String ?

 

Declaring a String variable is just like any other date type, but there are many different ways of assigning a string to the variable. This example shows you a couple of different ways of assigning values to the variable.

 

String01.java

public class String01 {

 

    public static void main(String[] args) {

        

        String s1 = "Hello World";

        String s2 = new String("Hello World");

        char cAry[]={'H','e','l','l','o',' ','W','o','r','l','d'};

        String s3 = new String(cAry);

        

        System.out.println(s1);

        System.out.println(s2);

        System.out.println(s3);

    }

 

}

 

 

    C:\temp> java String01

     

    Hello World <-- String s1 = "Hello World";

    Hello World <-- String s2 = new String("Hello World");

    Hello World <-- char cAry[]={'H','e','l','l','o',' ','W','o','r','l','d'};  String s3 = new String(cAry);

 

 

 

Methods of String Class

 

String class provides a lot of methods as listed below. I will not explain the syntax of each of these methods, I will show you the examples of these methods in various examples in this page and put the link to those same code.

 

 

 

 

How to compare two Strings ?

 

There are several different ways for string comparison as shown below.

 

StringCompare01.java

public class StringCompare01 {

 

    public static void main(String[] args) {

        

        String s1 = "Hello World";

        String s2 = "hello world";

        String s3 = "Hello World";

        

        System.out.println(s1 == s2);

        System.out.println(s1.equals(s2));

        System.out.println(s1.equals(s3));

        System.out.println(s1.equalsIgnoreCase(s2));

        System.out.println(s1.compareTo(s2));

        System.out.println(s2.compareTo(s1));

    }

 

}

 

 

    C:\temp> java StringCompare01

     

    false <-- System.out.println(s1 == s2);

    false <-- System.out.println(s1.equals(s2));

    true  <-- System.out.println(s1.equals(s3));

    true  <-- System.out.println(s1.equalsIgnoreCase(s2));

    -32   <-- System.out.println(s1.compareTo(s2));

    32    <-- System.out.println(s2.compareTo(s1));

 

 

StringCompare02.java

public class StringCompare02 {

 

    public static void main(String[] args) {

        

        String s1 = new String("Hello World");

        String s2 = "Hello World";

        

        System.out.println(s1 == s2);

        System.out.println(s1.intern() == s2);

        System.out.println(s1 == s2.intern());

        System.out.println(s1.equals(s2));

        System.out.println(s1.compareTo(s2));

    }

 

}

 

 

    C:\temp> java StringCompare01

     

    false    <-- System.out.println(s1 == s2);

    true     <-- System.out.println(s1.intern() == s2);

    false      <-- System.out.println(s1 == s2.intern());

    true       <-- System.out.println(s1.equals(s2));

    0        <-- System.out.println(s1.compareTo(s2));

 

 

How to find a String (substring) within a String ?

 

Personally I don't like the naming of string search function in Java. It took me quite a while to figure this out. It is indexOf() which searches a keyword from a string as shown below. It searches the keywords within a String and returns the position of the first character if it finds and return -1 if it cannot find the keyword. (This method is same as find() in Python). There is another method called contains(), but this method checks only whether the keyword can be found in a string or not, it does not return the position of the keyword as shown in the second example below.

 

StringIndexOf01.java

public class StringIndexOf01 {

 

    public static void main(String[] args) {

        

        String s1 = "This is an example for finding a subString within a String";

        

        System.out.println(s1.indexOf("example"));

        System.out.println(s1.indexOf("Example"));

        System.out.println(s1.indexOf("e"));

        System.out.println(s1.indexOf("This"));

        System.out.println(s1.indexOf("this"));

        System.out.println(s1.indexOf("This is"));

        System.out.println(s1.indexOf("T"));

        System.out.println(s1.indexOf("String"));

        System.out.println(s1.indexOf("String",37));

        System.out.println(s1.lastIndexOf("String"));

        System.out.println(s1.indexOf("string"));

        System.out.println(s1.indexOf("ng"));

    }

 

}

 

 

    C:\temp> java StringIndexOf01

     

    11    <-- System.out.println(s1.indexOf("example"));

    -1    <-- System.out.println(s1.indexOf("Example"));

    11    <-- System.out.println(s1.indexOf("e"));

    0     <-- System.out.println(s1.indexOf("This"));

    -1    <-- System.out.println(s1.indexOf("this"));

    0     <-- System.out.println(s1.indexOf("This is"));

    0     <-- System.out.println(s1.indexOf("T"));

    36    <-- System.out.println(s1.indexOf("String"));

    52    <-- System.out.println(s1.indexOf("String",37));

    52    <-- System.out.println(s1.lastIndexOf("String"));

    -1    <-- System.out.println(s1.indexOf("string"));

    28    <-- System.out.println(s1.indexOf("ng"));

 

 

 

StringContain01.java

public class StringContain01 {

 

    public static void main(String[] args) {

        

        String s1 = "This is an example for finding a substring within a String";

        

        System.out.println(s1.contains("example"));

        System.out.println(s1.contains("Example"));

        System.out.println(s1.contains("e"));

        System.out.println(s1.startsWith("This"));

        System.out.println(s1.startsWith("this"));

        System.out.println(s1.startsWith("This is"));

        System.out.println(s1.startsWith("T"));

        System.out.println(s1.endsWith("String"));

        System.out.println(s1.endsWith("string"));

        System.out.println(s1.endsWith("ng"));

    }

 

}

 

 

    C:\temp> java StringContain01

     

    true     <-- System.out.println(s1.contains("example"));

    false    <-- System.out.println(s1.contains("Example"));

    true     <-- System.out.println(s1.contains("e"));

    true     <-- System.out.println(s1.startsWith("This"));

    false    <-- System.out.println(s1.startsWith("this"));

    true     <-- System.out.println(s1.startsWith("This is"));

    true     <-- System.out.println(s1.startsWith("T"));

    true     <-- System.out.println(s1.endsWith("String"));

    false    <-- System.out.println(s1.endsWith("string"));

    true     <-- System.out.println(s1.endsWith("ng"));

 

 

 

How to split a String ?

 

This is one of the most commonly used function in my case. It is to split a string into multiple substring based on specified delimitor (e.g, whitespace, ',' etc).

 

StringSplit01.java

public class StringSplit01 {

 

    public static void main(String[] args) {

        

        String s1 = "This is an example        for splitting a String into  words (substrings)";

        String[] wordList = null;

        

        System.out.println("Split words (s1.split(\" \")) :----------------");

        wordList = s1.split(" ");  

 

        for(String w : wordList){  

            System.out.println(w);  

        }

        

        System.out.println("Split words (s1.split(\"\\s\")) :----------------");

        wordList = s1.split("\\s");  

 

        for(String w : wordList){  

            System.out.println(w);  

        }

        

        System.out.println("Split words (s1.split(\"\\s\",0)) :----------------");

        wordList = s1.split("\\s",0);  

 

        for(String w : wordList){  

            System.out.println(w);  

        }

        

        System.out.println("Split words (s1.split(\"\\s\",1)) :----------------");

        wordList = s1.split("\\s",1);  

 

        for(String w : wordList){  

            System.out.println(w);  

        }

        

        System.out.println("Split words (s1.split(\"\\s\",2)) :----------------");

        wordList = s1.split("\\s",2);  

 

        for(String w : wordList){  

            System.out.println(w);  

        }

        

        System.out.println("Split words (s1.split(\"\\s\",14)) :----------------");

        wordList = s1.split("\\s",14);  

 

        for(String w : wordList){  

            System.out.println(w);  

        }

    }   

 

}

 

 

    C:\temp> java StringSplit01

     

    Split words (s1.split(" ")) :----------------

    This

    is

    an

    example

     

     

     

     

     

     

     

    for

    splitting

    a

    String

    into

     

    words

    (substrings)

    Split words (s1.split("\s")) :----------------

    This

    is

    an

    example

     

     

     

     

     

     

     

    for

    splitting

    a

    String

    into

     

    words

    (substrings)

    Split words (s1.split("\s",0)) :----------------

    This

    is

    an

    example

     

     

     

     

     

     

     

    for

    splitting

    a

    String

    into

     

    words

    (substrings)

    Split words (s1.split("\s",1)) :----------------

    This is an example        for splitting a String into  words (substrings)

    Split words (s1.split("\s",2)) :----------------

    This

    is an example        for splitting a String into  words (substrings)

    Split words (s1.split("\s",14)) :----------------

    This

    is

    an

    example

     

     

     

     

     

     

     

    for

    splitting

    a String into  words (substrings)

 

 

 

How to replace a substring into another ?

 

replace() would be another most commonly used method. This method is to replace a substring (a segment of the string) with another string. In many of my program, I use this method to remove unecessary whitespace in a string as in the following example.

 

StringReplace01.java

public class StringReplace01 {

 

    public static void main(String[] args) {

        

        String s1 = "This is an example          for replacing a substring   (or a character) into  another)";

        String s2 = null;

        

        System.out.println("Original String :----------------");

        System.out.println(s1);

        

        System.out.println("Replace multi space into single space :----------------");

        s2 = s1.replace("  ","");  

        System.out.println(s2);

        

        System.out.println("Replace all the whitespace :----------------");

        s2 = s1.replaceAll("\\s","");  

        System.out.println(s2);

        

        System.out.println("Removing all the white space longer than one space :----------------");

        s2 = s1.replaceAll("   ","");

        s2 = s2.replaceAll("  "," ");       

        System.out.println(s2);

 

    }   

 

}

 

 

    C:\temp> java StringReplace01

     

    Original String :----------------

    This is an example          for replacing a substring   (or a character) into  another)

    Replace multi space into single space :----------------

    This is an examplefor replacing a substring (or a character) intoanother)

    Replace all the whitespace :----------------

    Thisisanexampleforreplacingasubstring(oracharacter)intoanother)

    Removing all the white space longer than one space :----------------

    This is an example for replacing a substring(or a character) into another)