Alternate way to concatenate 2 strings  

  • Previously, we learned that the concat( ) method can be used to concatenate 2 strings.

    Example:

      String s1 = "Hello 123";  // Create the first string
      String s2 = " Good-bye "; // Create the second string
    
      String result;
    
      result = s1.concat(s2); // String s1 concatenated with string s2
      result = s2.concat(s1); // String s2 concatenated with string s1
    

  • Java provides an alternate way to concatenate 2 strings using the  +  operator:

      result = s1  +  s2; // String s1 concatenated with string s2
      result = s2  +  s1; // String s2 concatenated with string s1
    

DEMO: demo/04-Math+String/05-string2/Concat.java

Comparing 2 strings: compareTo( )

  • We compare a string s1 with another string s2 using the compareTo( ) method:
     

      s1.compareTo(s2)      returns a value < 0  if   s1 preceeds  s2 
                            returns the value 0  if   s1 equals to s2
    			returns a value > 0  if   s1 succeeds  s2 
    

    Example how to use compareTo( ) to compare 2 strings:

      String s1, s2;
    
      s1 = input.next();   // Read in first string
      s2 = input.next();   // Read in secomd string
           
      if ( s1.compareTo(s2) < 0 )
         System.out.println(s1 + " preceeds " + s2);
      else if ( s1.compareTo(s2) > 0 )
         System.out.println(s1 + " succeeds " + s2);
      else if ( s1.compareTo(s2) == 0 )
         System.out.println(s1 + " is same as " + s2);
    

DEMO: demo/04-Math+String/05-string2/CompareTo.java

Comparing 2 strings ignoring case difference: compareToIgnoreCase( )

  • If we want to ignore the (upper/lower) case difference in the comparison, then use the compareToIgnoreCase( ) method:

      s1.compareToIgnoreCase(s2) returns a value < 0  if   s1 preceeds  s2 
                                 returns the value 0  if   s1 equals to s2
    			     returns a value > 0  if   s1 succeeds  s2 
    

    Example how to use compareTo( ) to compare 2 strings:

      String s1, s2;
    
      s1 = input.next();   // Read in first string
      s2 = input.next();   // Read in secomd string
           
      if ( s1.compareToIgnoreCase(s2) < 0 )
         System.out.println(s1 + " preceeds " + s2);
      else if ( s1.compareToIgnoreCase(s2) > 0 )
         System.out.println(s1 + " succeeds " + s2);
      else if ( s1.compareToIgnoreCase(s2) == 0 )
         System.out.println(s1 + " is same as " + s2);
    

DEMO: demo/04-Math+String/05-string2/CompareToIgnoreCase.java

Example using compareTo( )    ordering strings

Read in 2 strings into s1 and s2 and if necessary, swap the strings so that:   String s1 ≤ String s2:

   public static void main(String[] args) 
   {
       Scanner input = new Scanner(System.in);
       
       String s1, s2;

       System.out.print("Enter s1 = ");
       s1 = input.next();
       System.out.print("Enter s2 = ");
       s2 = input.next();
       
       if ( s1.compareTo(s2) > 0 )
       {
           String help;    // See: How to swap variables
           help = s1;      // Swap s1 and s2
           s1 = s2;
           s2 = help;
       }
       System.out.print(s1 + ", " + s2);
    }  

DEMO: demo/04-Math+String/05-string2/SwapStrings.java

2 ways to test if 2 strings are equal: equals( )

We have used compareTo( ) to test if string s1 is equal to string s2:   s1.compareTo(s2) == 0
We can also test if a string s1 is equal to another string s2 using:   s1.equals(s2)

   public static void main(String[] args) 
   {
       Scanner input = new Scanner(System.in);
       
       String s1, s2;

       System.out.print("Enter s1 = ");
       s1 = input.next();
       System.out.print("Enter s2 = ");
       s2 = input.next();

       if ( s1.compareTo(s2) == 0 )
          System.out.println(s1 + " is same as " + s2);
       else 
          System.out.println(s1 + " is different from " + s2);
     
       if ( s1.equals(s2) )   // SAME effec !!
          System.out.println(s1 + " is same as " + s2);
       else 
          System.out.println(s1 + " is different from " + s2);
   } 

DEMO: demo/04-Math+String/05-string2/Equals.java

Test if 2 strings are equal ignoring case difference: equalsIgnoreCase( )

To test if a string s1 is equal to another string s2 without considering case difference, we use the s1.equalsIgnoreCase(s2) method:

   public static void main(String[] args) 
   {
       Scanner input = new Scanner(System.in);
       
       String s1, s2;

       System.out.print("Enter s1 = ");
       s1 = input.next();
       System.out.print("Enter s2 = ");
       s2 = input.next();
       
       if ( s1.compareToIgnoreCase(s2) == 0 )
          System.out.println(s1 + " is same as " + s2);
       else 
          System.out.println(s1 + " is different from " + s2);
     
       if ( s1.equalsIgnoreCase(s2) )   // SAME effec !!
          System.out.println(s1 + " is same as " + s2);
       else 
          System.out.println(s1 + " is different from " + s2);
   } 

DEMO: demo/04-Math+String/05-string2/EqualsIgnoreCase.java

Test if string s1 starts with string s2:   startsWith( )

To test if string s1 starts with string s2, we use s1.startsWith(s2):

public class MyProg 
{
   public static void main(String[] args) 
   {
       Scanner input = new Scanner(System.in);
       
       String s1, s2;

       System.out.print("Enter s1 = ");
       s1 = input.next();
       System.out.print("Enter s2 = ");
       s2 = input.next();
       
       if ( s1.startsWith(s2) )
          System.out.println(s1 + " starts with " + s2);
       else 
          System.out.println(s1 + " does not start with " + s2);
   }
} 

DEMO: demo/04-Math+String/05-string2/StartsWith.java
Note:   Java does not have a StartsWithIgnoreCase( ) method.... but, we can do it with a progr. technique

Test if string s1 starts with string s2 ignoring case difference

Programming technique to ignore case difference:   (1) convert both strings to upper case and (2) compare

public class MyProg 
{
   public static void main(String[] args) 
   {
       Scanner input = new Scanner(System.in);
       
       String s1, s2;

       System.out.print("Enter s1 = ");
       s1 = input.next();
       System.out.print("Enter s2 = ");
       s2 = input.next();
       
       if ( (s1.toUpperCase()).startsWith(s2.toUpperCase()) )
          System.out.println(s1 + " starts with " + s2);
       else 
          System.out.println(s1 + " does not start with " + s2);
   }
}   

DEMO: demo/04-Math+String/05-string2/StartsWithNoCase.java

Test if string s1 ends with string s2:   endsWith( )

To test if string s1 starts with string s2, we use s1.endsWith(s2):

public class MyProg 
{
   public static void main(String[] args) 
   {
       Scanner input = new Scanner(System.in);
       
       String s1, s2;

       System.out.print("Enter s1 = ");
       s1 = input.next();
       System.out.print("Enter s2 = ");
       s2 = input.next();
       
       if ( s1.endsWith(s2) )
          System.out.println(s1 + " ends with " + s2);
       else 
          System.out.println(s1 + " does not end with " + s2);
   }
} 

DEMO: demo/04-Math+String/05-string2/EndsWith.java

Test if string s1 contains string s2:   contains( )

To test if string s1 contains string s2, we use s1.contains(s2):

public class MyProg 
{
   public static void main(String[] args) 
   {
       Scanner input = new Scanner(System.in);
       
       String s1, s2;

       System.out.print("Enter s1 = ");
       s1 = input.next();
       System.out.print("Enter s2 = ");
       s2 = input.next();
       
       if ( s1.contains(s2) )
          System.out.println(s1 + " contains " + s2);
       else 
          System.out.println(s1 + " does not contain " + s2);
   }
} 

DEMO: demo/04-Math+String/05-string2/Contains.java

Substrings

  • Substring:

    • A substring is a part of some string

    Example:

       s1 = "Welcome";
      
       Substrings of s1 are:       
      
           "W"  "We"  "Wel"  "Welc"  ...          
           "e"  "el"  "elc"  "elco"  ...
           ....
      

  • There are 2 methods in Java that return substrings:

       substring(i1)      // string from char pos i1 (till the end)    
      
       substring(i1, i2)  // string from char pos i1 to i2 (not including) 
      

Forming substrings with substring(index1)

  • The characters in a string s are identified by a position index as follows:

             0123456   <--- position index   
        s = "Welcome";

  • s.substring(index1):

    • returns the substring of string s consisting of the characters at the position index1 until the end of the string

    Examples:

                    0123456   <--- position index   
       String s1 = "Welcome";
      
       System.out.println( s1.substring( 0 ) );  // Prints "Welcome" 
       System.out.println( s1.substring( 1 ) );  // Prints "elcome"
       System.out.println( s1.substring( 3 ) );  // Prints "come"
      

DEMO: demo/04-Math+String/05-string2/Substring1.java

Cyclic sequences:    an application using substring(index1)

  • Cyclic sequence:

    • A cyclic sequence is a string obtained from another string by rotating the characters in the string

    Example:

       The cyclic sequences of  ABCD are:
      
           ABCD   BCDA   CDAB  DABC

  • Programming problem:

      • Write a Java program that prints all the the cyclic sequences of ABC123

Cyclic sequences:    an application using substring(index1)

  • How to make the next cyclic subsequence of a string:

       Suppose  s = "ABC123"       Next cyclic sequence = "BC123A"
      
       How to make the next cyclic sequence:
      
           s.substring(1) = "BC123"
           s.charAt(0)    = 'A'
      
       Therefore:
      
           s.substring(1) + s.charAt(0) = "BC123A"

  • Solution:

       String s = "ABC123"; 
      
       s = s.substring(1) + s.charAt(0);  // Next cyclic sequence
       s = s.substring(1) + s.charAt(0);  // Next cyclic sequence
       ... (repeat 3 more times) 

DEMO: demo/04-Math+String/05-string2/CyclicSeq.java

Forming substrings with substring(index1,index2)

  • Recall that the characters in a string s are identified by an index as follows:

             0123456   <--- position index   
        s = "Welcome";

  • s.substring(index1, index2):

    • returns the substring of string s that begins with the character at the position index1 until (not including) the character at the position index2

    Examples:

                    0123456   <--- position index   
       String s1 = "Welcome";
      
       System.out.println( s1.substring(1, 7) );  // Prints "elcome" 
       System.out.println( s1.substring(1, s.length()) );  // Same
       System.out.println( s1.substring(1, 4) );  // Prints "elc" 
      

DEMO: demo/04-Math+String/05-string2/Substring2.java

Finding substrings:    indexOf(substring)

  • Recall that the characters in a string s are identified by an index as follows:

            0123456789    <--- position index
       s = "XABCXXABCX";

  • s.indexOf(substring):

    • returns the position index of the first occurence of substring substring in the string s if found, otherwise returns -1

    Examples:

           0123456789
     s1 = "XABCXXABCX"
    
     s1.indexOf("ABC")     returns 1
     s1.indexOf("XX")      returns 4
     s1.indexOf("XY")      returns -1
    

DEMO: demo/04-Math+String/05-string2/IndexOf1.java

Finding substrings:    indexOf(substr, s)

  • Recall that the characters in a string s are identified by an index as follows:

            0123456789    <--- position index
       s = "XABCXXABCX";

  • s.indexOf(substring, startpos):

    • returns the position index of the first occurence of substring substring in the string s starting at start position startpos

    Examples:

           0123456789
     s1 = "XABCXXABCX"
    
     s1.indexOf("ABC", 0)     returns 1
     s1.indexOf("ABC", 1)     returns 1
     s1.indexOf("ABC", 2)     returns 6
    

DEMO: demo/04-Math+String/05-string2/IndexOf2.java

Example using indexOf( )    split full name into first name and last name

 Given a string containing a full name:

     String s1 = "James Bond";

 Problem:

     Assign first name to variable firstName    and
     assign last name to variable lastName


Solution: (1) Find the position of the SPACE character in the full name int k = s1.indexOf(" "); // "James Bond" // ^ // k (2) Form 2 substrings but "cutting" at this position: String firstName = s1.substring(0, k); String lastName = s1.substring(k+1);

DEMO: demo/04-Math+String/05-string2/SplitName.java