Create user defined substring functions

 

In many interviews we may asked to substring() a string without using substring function from String class. Below are the simple code how we can write our own substring functions similar to String class functions.


public class MyStringOp {

 public static void main(String[] args) {
  
  String str = "Java Discover";
  
  MyStringOp obj = new MyStringOp();
  
  System.out.println(obj.mySubstring(str, 5));
  
  System.out.println(obj.mySubstring(str, 0,4));
 }
 
 public String mySubstring(String str, int start){
  
  if(start > str.length()) 
   throw new StringIndexOutOfBoundsException(); 
  
  String newStr = "";
  char[] ch = str.toCharArray();
  
  for(int i=start;i<str.length();i++){
   newStr = newStr + ch[i];
  }
  return newStr;
 }
 
 public String mySubstring(String str, int start, int end){
  
  if((start > end) || (start > str.length()) || (end > str.length())) 
   throw new StringIndexOutOfBoundsException(); 
  
  String newStr = "";
  char[] ch = str.toCharArray();
  
  for(int i=start;(i<str.length() && i<end);i++){
   newStr = newStr + ch[i];
  }
  return newStr;
 }
}




OUTPUT:


Discover
Java


No comments:
Write comments