In: Computer Science
How would you write the following recursively? This is in Java.
public static String allTrim(String str) {
int j = 0;
int count = 0; // Number of extra spaces
int lspaces = 0;// Number of left spaces
char ch[] = str.toCharArray();
int len = str.length();
StringBuffer bchar = new StringBuffer();
if (ch[0] == ' ') {
while (ch[j] == ' ') {
lspaces++;
j++;
}
}
for (int i = lspaces; i < len; i++) {
if (ch[i] != ' ') {
if (count > 1 || count == 1) {
bchar.append(' ');
count = 0;
}
bchar.append(ch[i]);
} else if (ch[i] == ' ') {
count++;
}
}
return bchar.toString();
}
Solution:
class Main
{
//recursive function
static String trimAll(String str, int start, int end)
{
if(str.charAt(start)!=' ' && str.charAt(end)!=' ')
{
return str.substring(start, end+1);
}
else if(str.charAt(start)==' ' && str.charAt(end)!=' ')
{
return trimAll(str, start+1, end);
}
else if(str.charAt(start)==' ' && str.charAt(end)==' ')
{
return trimAll(str, start+1, end-1);
}
else
{
return trimAll(str, start, end-1);
}
}
//main function
public static void main(String[] args) {
String str = " India ";
//length of original string
System.out.println("Original string = "+str+ "\nOriginal string length = "+str.length());
String result = trimAll(str, 0, str.length()-1);
//to count extra spaces you just need to get the length difference
int extraSpaces = str.length() - result.length();
System.out.println("Extra spaces = " +extraSpaces);
//length of string after trimming
System.out.println("Resultant string = "+result+ "\nResultanat string length = " +result.length());
}
}
Output:
Please give thumbsup, if you like it. Thanks.