Wednesday, June 15, 2016

allStar - Recursive - Java & C#

Given a string, compute recursively a new string where all the adjacent chars are now separated by a "*".

allStar("hello") → "h*e*l*l*o"
allStar("abc") → "a*b*c"
allStar("ab") → "a*b"
Java :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public static String allStar(String str)
 {
  //Stop Condition
  if(str.length()<1) return "";
  if(str.length() == 1) return str+"*";
  
  
  //Main recursive process
  return str.charAt(0)+"*"+allStar(str.substring(1));
 }

Hasil :

C# :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
   public static string allStar(String str)
        { 
            //Kondisi stop
            if (str.Length < 1) return "";
            if (str.Length == 1) return str;


            //Proses rekursif
            return str[0] + "*" + allStar(str.Substring(1));
        }

Hasil :

No comments:

Post a Comment