Friday, May 19, 2017

Java String Example

May 19, 2017

String in Java
java string

Strings Example

Example 1:

Get first two characters of any String
public String firstTwo(String str) {
  if (str.length() >= 2) {
    return str.substring(0, 2);
  } else {
    return str;
  }
  // Solution notes: need an if/else structure to call substring if the length
  // is 2 or more, and otherwise return the string itself
} 

Alternative example of getting first two characters of any strings

public String firstTwo(String str) {

    if (str.length() >= 2) {

        char s = str.charAt(0);
        char s1 = str.charAt(1);

    String string = String.valueOf(s) + s1;
 
 return string;
  }
  return str;
}

Example 2:

get last two characters of any string
public static void main(String[] args) {

    String str = "hello";

    System.out.println(str.substring(str.length()-2));
}

Example 3:

Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
public String firstHalf(String str) {
  return str.substring(0,(str.length())/2); 
}

Example 4:

Given a string, return a new version without the first and last character
public String withoutEnd(String str) {
    return str.substring(1,str.length()-1);
  }

Example 5:

Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside
public String comboString(String a, String b) {
  
  int a1 = a.length();
  
  int b1 = b.length();
  
  if(a1 > b1){
     return b+a+b;
  }
  
  return a+b+a;
}

Example 6:

Given 2 strings, return their concatenation, except omit the first char of each.
public String nonStart(String a, String b) {
  
    String s = a.substring(1,a.length());
  
 String s1 = b.substring(1,b.length());
 
 return s+s1;
}

Example 7:

Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end
public String left2(String str) {
  
  if (str.length() >= 2) {
   String s = str.substring(0, 2);
   String s1 = str.substring(2, str.length());
   
   return s1+s;
  }
  return str;
}

Read More