How to Remove Zeros in Java Recursion
Removing the zeros from a String with recursion is helpful when you need to format numbers that may have extra zeros padded on the front. Recursion is a powerful programming technique in Java where a function repeatedly calls itself, dividing a problem into a series of smaller sub-problems. Remove the zeros from a String by creating a recursive function that checks if the first character in the String is a zero and, if so, recursively returns a smaller version of the String.
Instructions
-
-
1
Open your Java source file in an editor such as Netbeans, Eclipse or JBuilder X.
-
2
Create a function that will recursively remove zeros from the beginning of a String by adding the following code above your main function:
public String function remove_zeros(String str) {
if (str.length()>0) {
if (str.charAt(0)=='0') {
return remove_zeros(str.substring(1));
}
}
return str;
}
The function checks if the String's length is greater than 0 and retrieves the value of the first character. If the first character is a "0," the function calls itself recursively, passing a value of the String without the beginning "0." This continues until the function encounters a non-zero character or the String ends.
-
-
3
Call the recursive function and display its result by adding the following code in your main function:
String str = "0003.14159";
String modified_str = "";
modified_str = remove_zeros(str);
System.out.println(modified_str);
The code will display the String "3.14159" with the zeros removed.
-
4
Save your Java source file; compile and execute the program to recursively remove the zeros from your String.
-
1