The challenge: Given a String, for each digit in that original string, replace that digit with that many occurrences of the character following it. So a3tx2z
yields attttxzzz
.
My Solution:
import java.util.Scanner;
public class Standford1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter string to blowup: ");
String userInput = input.nextLine();
System.out.println(blowup(userInput));
}
public static String blowup(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (!isNumeric(str.substring(i, i + 1))) {
sb.append(str.charAt(i));
}
else {
sb.append(lengthen(str.charAt(i + 1),
Integer.parseInt(str.substring(i, i + 1))));
}
}
return sb.toString();
}
public static boolean isNumeric(String str) {
try {
int num = Integer.parseInt(str);
}
catch(NumberFormatException nfe) {
return false;
}
return true;
}
public static String lengthen(char c, int i){
if (i == 0 || c == ' ') { return ""; }
int count = 0;
StringBuilder sb = new StringBuilder(c);
while (count != i) {
sb.append(c);
count++;
}
return sb.toString();
}
}
Could this be more readable? I alternate a lot between char and string (it seems optimal, am I wrong?), but should I just stick with one? Any and all feedback/suggested revisions/general optimizations welcomed with gratitude.
Edit: Stay within the specifications of the challenge. In the case of a number following a number this code is WAI i.e. the correct yield of blowup("a231") results in "a33111."
Edit 2: End digits just get ignored, since they have nothing to repeat, i.e. blowup("a2x3") would yield "axxx" - I realize I overlooked this case due to a question below, I have now amended this, but left the original question and code intact.
Edit 3: These should all be true:
/* Two plain cases */
System.out.println("Test 1: " + "xxaaaabb".equals(blowup("xx3abb")));
System.out.println("Test 2: " + "xxxZZZZ".equals(blowup("2x3Z")));
/* digit at the end */
System.out.println("Test 3: " + "axxx".equals(blowup("a2x3")));
/* Adjacent digits */
System.out.println("Test 4: " + "a33111".equals(blowup("a231")));
/* Digit include 0 */
System.out.println("Test 5: " + "aabb".equals(blowup("aa0bb")));
/* Unusual Characters */
System.out.println("Test 6: " + "AB&&,- ab".equals(blowup("AB&&,- ab")));
/* Empty String */
System.out.println("Test 7: " + "".equals(blowup("")));
/* Only digits */
System.out.println("Test 8: " + "".equals(blowup("2")));
System.out.println("Test 9: " + "33".equals(blowup("23")));
Note: So this isn't incorrectly perceived as a 'do this for me' question, as stated in edit 2, I've already accounted for all cases.