I have been messing around with recursion today. Often a programming technique that is not used enough.
I set out to recursively reverse a string. Here's what I came up with:
//A method to reverse a string using recursion
public String reverseString(String s){
char c = s.charAt(s.length()-1);
if(s.length() == 1) return Character.toString(c);
return c + reverseString(s.substring(0,s.length()-1));
}
My question: is there a better way in Java?
The best way is not to use recursion. These stuff are usually used to teach students the recursion concept, not actual best practices. So the way you're doing it is just fine. Just don't use recursion in Java for these kind of stuff in real world apps ;)
PS. Aside what I just said, I'd choose "" as the base case of my recursive function:
public String reverseString(String s){
if (s.length() == 0)
return s;
return reverseString(s.substring(1)) + s.charAt(0);
}
If you're going to do this, you want to operate on a character array, because a String is immutable and you're going to be copying Strings all over the place if you do it that way.
This is untested and totally stream of consciousness. It probably has an OB1 somewhere. And very not-Java.
public String reverseString(String s)
{
char[] cstr = s.getChars();
reverseCStr(cstr, 0, s.length - 1);
return new String(cstr);
}
/**
* Reverse a character array in place.
*/
private void reverseCStr(char[] a, int s, int e)
{
// This is the middle of the array; we're done.
if (e - s <= 0)
return;
char t = a[s];
a[s] = a[e];
a[e] = t;
reverseCStr(a, s + 1, e - 1);
}
You don't want to nest too deeply. Divide-and-conquer is the way to go. Also reduces total size of temporary strings and is amenable to parallelisation.
public static String reverseString(String str) {
int len = str.length();
return len<=1 ? str : (
reverseString(str.substring(len/2))+
reverseString(str.substring(0, len/2))
);
}
(Not tested - this is stackoverflow.)
String.concat instead of + would improve performance at the expense of clarity.
Edit: Just for fun, a tail-recursion friendly version of the naive algorithm.
public static String reverseString(String str) {
return reverseString("", str);
}
private static String reverseString(String reversed, String forward) {
return forward.equals("") ? reversed : (
reverseString(reversed+forward.charAt(0), forward.substring(1))
);
}
Correct handling of surrogate pairs is left to the interested reader.
here is my recursive reverse function that is working fine
public static String rev(String instr){
if(instr.length()<=1){
return instr;
} else {
return (instr.charAt(instr.length()-1)+rev(instr.substring(0,instr.length()-1)) );
}
}
Just for the heck of it, here's a tail-recursive method using StringBuilder (which is generally recommended over manipulating Strings).
public String reverseString(String s_) {
StringBuilder r = new StringBuilder();
StringBuilder s = new StringBuilder(s_);
r = reverseStringHelper(r, s);
return r.toString();
}
private StringBuilder reverseStringHelper(StringBuilder r, StringBuilder s) {
if (s.length() == 0)
return r;
else
return reverseStringHelper(r.append(s.charAt(0)), s.deleteCharAt(0));
}
Untested, I haven't dealt with Java in many years, but this should be about right.
If you're writing real code (not learning recursion), use StringBuilder's reverse() method. The Java Tutorial gives this example:
String palindrome = "Dot saw I was Tod";
StringBuilder sb = new StringBuilder(palindrome);
sb.reverse(); // reverse it
System.out.println(sb);
It depends on what you define as "better". :-) Seriously, though; your solution essentially uses the maximum depth of recursion; if stack size is of a concern for your definition of "better", then you'd be better off using something like this:
public String reverseString(String s) {
if (s.length() == 1) return s;
return reverseString(s.substring(s.length() / 2, s.length() -1) + reverseString(0, s.length() / 2);
}
This is what I've found to work and use recursive. You can pass str.length() as strLength argument
private static String reverse(String str, int strLength) {
String result = "";
if(strLength > 0)
result = str.charAt(strLength - 1) + reverse(str, strLength - 1);
return result;
}
In Java, since the String is immutable, the String concatenation would be more complex than it looks like.
For every concatenation, it creates a new string copying the contents of original String resulting in a linear complexity O(n) where n is the length of the string, so for m such operations it is O(m*n), we can say it is of quadratic complexity O(n^2).
We can use a StringBuilder which has O(1) complexity for each append. Below is the recursive program using StringBuilder. This uses only n/2 stack frames, so it has less space complexity than the normal recursive call which would be like s.charAt(s.length-1) + reverse(s.subString(0, s.length-2);
public class StringReverseRecursive {
public static void main(String[] args) {
String s = "lasrever gnirts fo noitatnemelpmi evisrucer a si sihT";
StringBuilder sb = new StringBuilder(s);
reverse(s, sb, 0, sb.length() - 1);
System.out.println(sb.toString());
}
public static void reverse(String s, StringBuilder sb, int low, int high) {
if (low > high)
return;
sb.setCharAt(low, s.charAt(high));
sb.setCharAt(high, s.charAt(low));
reverse(s, sb, ++low, --high);
}
}
That's definitely how I'd go about recursively reversing a string (although it might be nice to extend it to the case of an empty string in your condition.) I don't think there is any fundamentally better way.
EDIT: It may be more efficient to operate on a character array and pass a "cutoff" length down the chain of recursion, if you get my drift, rather than making substrings. However, this is not really worth nitpicking about, since it's not a terribly efficient technique in the first place.
You capture the basic idea, but extracting the last character doesn't improve clarity. I'd prefer the following, others might not:
public class Foo
{
public static void main(String[] argv) throws Exception
{
System.out.println(reverse("a"));
System.out.println(reverse("ab"));
System.out.println(reverse("abc"));
}
public final static String reverse(String s)
{
// oft-repeated call, so reduce clutter with var
int length = s.length();
if (length <= 1)
return s;
else
return s.substring(length - 1) + reverse(s.substring(0, length - 1));
}
}
As Mehrdad noted, it's best not to use recursion. If you do use it, though, you might as well keep both the first and last character each call, thus halving the number of recursive calls. That is,
public String reverseString(String s){
int len = s.length();
if (len <= 1) {
return s;
}
char fst = s.charAt(0);
char lst = s.charAt(len - 1);
return lst + reverseString(s.substring(1, len - 2)) + fst;
}
This also handles the case of the empty string. Perhaps passing along a StringBuilder with the appropriate capacity would speed things up even more, but that's left as an exercise to the reader ;)
You can try with an external variable, and add 1 by 1 all chars:
public static String back="";
public static String reverseString(String str){
if(str.length()==0){
return back;
}else {
back+=str.charAt(str.length()-1);
lees(str.substring(0,str.length()-1));
return back;
}
}
Here is my immutable version:
String reverse(String str) {
if(str.length()<2) return str;
return reverse(str.substring(1)) +str.charAt(0);
}
and tail recursive version:
String reverseTail(String str) {
if(str.length()<2) return str;
return str.charAt(str.length()-1)+ reverseTail(str.substring(0,str.length()-1));
In this context, this is totally unnecessary, but you can simulate recursion and avoid recursion depth issues if you make your own stack.
You can iterative implement recursion, which may be necessary when you have algorithms which are inherently recursive, but also need to run them for big problem sizes.
String recIterReverse (String word){
Stack <String> stack = new Stack <String> ();
stack.push(word);
String result = "";
while (!stack.isEmpty()){
String temp = stack.pop();
result = temp.charAt(0) + result;
if (temp.length() > 1){
stack.push(temp.substring(1));
}
}
return result;
}
function call:
//str:string to be reversed,i=0,j=str.length-1
public void reverseString(String str,int i,int j)
{
if(i==j)
{
System.out.println(str);
return;
}
char x=str.charAt(i);
str=str.replace(str.charAt(i),str.charAt(j));
str=str.replace(str.charAt(j),x);
i++;j--;
reverseString(str,i,j);
}
this method works too..
Try the following:
public class reverse2
{
public static void main(String name)
{
String revname=new StringBuffer(name).reverse().toString();
System.out.println("original string " + name + " and the reverse of it is " + revname);
}
}
public static String rev(String name){
if(name.length()>=1){
System.out.print(name.charAt(name.length()-1));
return rev(name.substring(0,name.length()-1));
}
else{
return ""+name.substring(0);
}
}
String rev="";
public String reverseString(String s){
if (s.length()==0) return "";
return rev+s.substring(s.length()-1,s.length())+reverseString(s.substring(0, s.length()-1));
}
public String reverseString (String s) {
if (s != null && s.length () > 0 ) {
rev = rev + s.substring (s.length () - 1);
reverseString (s.substring (0, s.length () - 1));
}
return rev;
}
public class StringUtility {
public static void main(String[] args) {
StringUtility stringUtility = new StringUtility();
String input = "santosh123";
int middle = input.length() / 2;
middle = middle - 1;
System.out.println(stringUtility.stringReverse(input, middle));
}
public String stringReverse(String input, int middle) {
if (middle == -1) {
System.out.println("if");
return input;
} else {
System.out.println("else");
input = swapChar(input, middle);
middle = middle - 1;
return stringReverse(input, middle);
}
}
private String swapChar(String input, int middle) {
StringBuilder str = new StringBuilder(input);
char begin = str.charAt(middle);
int endIndex = input.length() - middle - 1;
char end = str.charAt(endIndex);
str.setCharAt(middle, end);
str.setCharAt(endIndex, begin);
System.out.println(str + " " + middle + " " + endIndex);
return str.toString();
}
}
If you think less code is good then....
static String reverse(String str){
return str.length()>=2 ? str.charAt(str.length()-1) + reverse(str.substring(0,str.length()-1)) : str ;
}
There are about 20 answers already but I'll just throw in my recursive algorithm as well. It may be a little verbose but it is at least readable.
public static String reverseString(String str) {
return reverseString("", str);
}
private static String reverseString(String result, String original) {
if (original.length() == 0) {
return result;
} else {
int length = original.length();
String lastLetter = original.substring(length - 1, length);
original = original.substring(0, length - 1);
return reverseString(result + lastLetter, original);
}
}
The code basically recursively takes the end of the string and moves it in front. For example if the string we want to reverse is "jam," then each time the helper method is called, result and original strings are as follows:
// result: original:
// "" jam
// m ja
// ma j
// maj ""
Reverse String using the recursive method call.
Sample Code
public static String reverseString(String s) {
if (s.length() == 0) {
return s;
}
else {
return s.charAt(s.length() - 1) + reverseString(s.substring(0, s.length() - 1));
}
}
This is my solution,I saw in many solutions above we are getting the string length but ideally we don't need that. The Zen is to use recursion, just chop the first char of string and pass the rest to recursive method. Yay!! we got the solution.
private static void printReverse(String str) {
if (!str.isEmpty()) {
String firstChar = str.substring(0, 1); //Get first char of String
String newstr = str.substring(0, 0) + str.substring(1); // Get remaining string
printReverse(newstr); // Recursion magic
System.out.print(firstChar); //Output
}
}
public static String reverse(String s){
int n = s.length()-1;
if(n >=0)
return s.substring(s.length()-1)+ReverseString(s.substring(0,n--));
else return "";
}
Related
The question is pretty self explanatory...Design a method called startChar(String str, char c). This is a code i found here but it insert char at the end of the String. I am at a loss to think recursively. I understand this code but dont understand it enough to manipulate it to place chars at the start. Help of any kind is appreciated.
Example Input:
startChar("Apple",'p')
Output:
ppale
The code
public static String chrToLast(String str, char ch) {
//This if statement details the end condition
if(str.length() < 1) {
return "";
}
String newString = str.substring(1); //Create new string without first
character
if(str.indexOf(ch) == 0) { //This happens when your character is found
return chrToLast(newString, ch) + ch;
} else { //This happens with all other characters
return str.charAt(0) + chrToLast(newString, ch);
}
}
What about...
public static void main(String[] args) {
String s = startChar("Apple", 'p');
System.out.println("");
}
public static String startChar(String str, char ch) {
return startChar(str,ch,"","");
}
private static String startChar(String str, char ch, String acc, String chs) {
//This if statement details the end condition
if (str.length() < 1) {
return chs + acc;
}
String newString = str.substring(1); //Create new string without first character
if(str.charAt(0) == ch) { //This happens when your character is found
return startChar(newString, ch,acc, chs + ch);
} else { //This happens with all other characters
return startChar(newString, ch,acc+str.charAt(0), chs);
}
}
This is recursive with a auxiliary function
UPDATE: you must know/remember that you can procesate your data before and after the recursive call, but try to write your recursive call at the end, generally most languages has optimization in that case.
In this example we use an accumulator to accumulate processed data, then in the base step we processed those accumulator to the final output.
I am trying to write a recursion where a word is trying mirror itself (appleelppa). MY thought process is to with a recursion that prints out the word in reverse order and then add the word in the beginning. However, this did not work somehow. here is my code,
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return str + reverse(str.substring(1)) + str.charAt(0);
}
this is the output: ellepplepppleaapple
Any help?
Thanks
Your reverse routine is almost correct (but you really should add a mirror routine, your method is confused as is). You want something like this,
// Reverse the input String str.
private static String reverse(String str) {
// This just looked ugly.
if (str == null || str.length() <= 1) {
return str;
}
// this is how you recursively reverse the word.
return reverse(str.substring(1)) + str.charAt(0);
}
// mirror is trivial, the word and the reverse of the word.
public static String mirror(String str) {
return str + reverse(str);
}
public static void main(String[] args) {
String str = "apple";
System.out.println(mirror(str));
}
Output is (as requested)
appleelppa
EDIT
// mirror an input string iteratively.
public static String mirror(String str) {
// return str + reverse(str);
StringBuilder sb = new StringBuilder(str);
return str + sb.reverse().toString();
}
All the answers you were given gave you new solutions. I'm here to tell you your solution is 90% correct.
Remove str + from:
return str + reverse(str.substring(1)) + str.charAt(0);
To make:
return reverse(str.substring(1)) + str.charAt(0);
And your original function works like a charm ;)
It would be much simpler if you just wrote a recursive function to reverse the string, and then added it to the original.
public class Reverse{
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
System.out.println("appleelppa" + reverse("appleelppa"));
}
}
The ugly hack to use exactly how one method with recursion and not iteration.
Note that this is not the preferred way to do things. It is only placed here to show the OP that it can be done, since he was curious. This is inspired by a comment from AdrianShum.
public class Reverse{
public static String mirror(String str, boolean firstCall) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
if (firstCall)
return str + mirror(str.substring(1), false) + str.charAt(0);
else
return mirror(str.substring(1),false) + str.charAt(0);
}
public static void main(String[] args) {
System.out.println(mirror("appleelppa", true));
}
}
Another not ugly recursive approach:
public static String mirror(String s) {
if (s == null || s.isEmpty()) {
return "";
}
return s.charAt(0) + mirror(s.substring(1)) + s.charAt(0);
}
In brief, mirroring a string means having a string with the first character, then the mirrored remainings, and then the first character again.
(Edit: just updated with actual code that I have tested which works)
For the code i need to write a method the decompresses a string. For example if the user entered "2d5t" the method would return "ddttttt". My code now will work for that input but if the input uses a character without a number before it the program wont work when it should. For example if the input was just "d" the program wouldnt work instead of just returning "d". The code also has to be recursive.
Here is what my code is now please help.
public static String decompress(String compressedText) {
if (compressedText.equals(""))
return "";
return decompress(compressedText, charInt(compressedText, 0), 0);
}
public static String decompress(String text, int count, int pos) {
if (pos == text.length() || (pos == text.length()-2 && count == 0))
return "";
else if (count == 0)
return decompress(text, charInt(text, pos+2), pos+2);
return text.charAt(pos+1) + decompress(text, count-1, pos);
}
public static int charInt(String str, int idex) {
return str.charAt(idex) - '0';
}
Here's some pseudocode:
function createString(int times, char character){
if times is 0, do nothing
otherwise return character + createString(times-1, character);
}
function createString(string full){
split string by number/character pairs
for each pair, call createString(times, character), and append them
}
I don't believe in handing out real code, sorry. It's much better in the long run.
You need to validate your user input. Decide first, that what string values are acceptable to your method and then write a validate method. Then invoke that method inside your decompress method.
Look into string manipulation functions and regular expressions in Java. And then try rewriting your code.
As mentioned by others, this can be solved with regular expressions. An example solution is:
public static String decompress(String compressed) {
Matcher matcher = Pattern.compile("(\\d+)([^\\d])").matcher(compressed);
StringBuffer decompressed = new StringBuffer();
while (matcher.find()) {
Integer charNum = Integer.parseInt(matcher.group(1));
StringBuilder decompressedChars = new StringBuilder();
for (int i = 1; i <= charNum; i++) {
decompressedChars.append(matcher.group(2));
}
matcher.appendReplacement(decompressed, decompressedChars.toString());
}
matcher.appendTail(decompressed);
return decompressed.toString();
}
This code won't support numbers larger than Integer.MAX_VALUE and you might want to put some error handling and validation in there also.
**Edited to be recursive as per the OP's request
Tested left first one char lookahead parser using regex
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Parser{
private static String parse(StringBuilder output, String input, Integer offset){
if(offset<input.length()){
java.util.regex.Pattern p0 =
java.util.regex.Pattern.compile("\\d(?=[a-z])");
java.util.regex.Pattern p1 =
java.util.regex.Pattern.compile("[a-z]");
java.util.regex.Matcher m0 = p0.matcher(input);
java.util.regex.Matcher m1 = p1.matcher(input);
if (m0.find(offset) && m0.start() == offset)
{
for(Integer i = 0;
i < Integer.parseInt(String.valueOf(input.charAt(offset)));
++i) {
output.append(input.charAt(offset+1));
}
offset+=2;
}
else if (m1.find(offset) && m1.start() == offset) {
output.append(input.charAt(offset));
++offset;
}
else {
++offset;
}
return parse(output, input, offset);
}
else return output.toString();
}
public static void main(String[] args)
{
Integer offset = 0;
StringBuilder output = new StringBuilder();
parse(output, args[0], offset);
System.out.println(output.toString());
}
}
For example, if I call exchangePairs("abcdefg"), I should receive "badcfeg" in return.
This is for a homework assignment, any kind of pseudocode would be very helpful. I am just beginning to learn recursion and up until this problem I haven't had too much of an issue.
public String swapPairs(String s) {
if (s.length() < 2)
return s;
else
return swap(s.charAt(0), s.charAt(1)) + swapPairs(s.substring(2));
}
You're not just beginning to learn recursion, because recursion is part of your everyday live. You just don't notice, because it is so normal and nobody calls it recursion.
For example, you watch a movie on TV, and in one scene there is someone watching a movie on TV.
In programming, recursion is a way to make hard things easy. Always start with the easy case:
What is the result of exchangePairs("")?
What is the result of exchangePairs("x") where x is any character?
Suppose you have already completed exchangePairs(), how would the result be for "xy..." where "..." is any string? Surely "yx+++", where "+++" is the result of exchangePairs("...").
Now, it turns out that we've covered all cases! Problem solved!
Such is the greatness of recursion. You just use your function as if it were complete despite you've not completed it yet.
Why use recursion?
for (int i = 0; i + 1 < strlen(str); ++i) {
char tmp = str[i + 1];
str[i + 1] = str[i];
str[i] = tmp;
}
If you have to use recursion, I suppose you could do something like this:
char* exchangePairs(char* str) {
if (strlen(str) >= 2) {
// if there are characters left, swap the first two, then recurse
char tmp = str[1];
str[1] = str[0];
str[0] = str[1];
exchangePairs(str + 2);
}
return str;
}
That's in C, but it should give you the idea (I'm better in C and didn't want to just give you a copy/pasteable solution).
Use tail recursion
String reverse(String input)
{
if(String.length()==1)
{
return input;
}
else
{
return reverse(input,"");
}
}
String reverse(String input, String result)
{
if(input.length == 0) return result;
else return result(input.substring(1),input.charAt(0) + result);
}
Ok Here is my solution. I dont have Java at my disposal so I did it in C# which is very similar to Java so should be easy to understand/port;
public static char[] exchangePairs(char[] charArray, int current)
{
if(current >= charArray.Length - 1)
{
return charArray;
}
char nextChar = charArray[current + 1];
char currentChar = charArray[current];
charArray[current] = nextChar;
charArray[current + 1] = currentChar;
int i = current + 2;
return exchangePairs(charArray, i);
}
Call to the method:
exchangePairs("abcdefghij".ToCharArray(), 0);
public static String swapPairs(String s) {
String even = "";
String odd = "";
int length = s.length();
for (int i = 0; i <= length-2; i+=2) {
even += s.charAt(i+1) + "" + s.charAt(i);
}
if (length % 2 != 0) {
odd = even + s.charAt(length-1);
return odd;
} else {
return even;
}
}
A small adding on Steven's solution, you can use StringBuffer/StringBuilder.reverse() for reversing a string.
public String swapPairs(String s) {
if (s.length() < 2)
return s;
else {
return new StringBuffer(s.substring(0, 2)).reverse().toString() + swapPairs(s.substring(2));
}
}
I'd introduce an integer recursion control variable which is how much of the string has already been exchanged. At each level, check the control variable to see if there's more to do and, if so, exchange the next pair, increment by 2, and recurse.
Every other question I have seen in my book I had at least some understanding of what the book was asking but this one I have no idea on how to approach it. It goes:
"Write a method called padString that accepts two parameters: a String and an integer representing a length. For example,
padString ("hello", 8)
should return "hello " (that's three spaces in there at the end). If the string's length is already at least as long as the length parameter, your method should return the original string. For example,
padString ("congratulations", 10)
should return "congratualtions".
I have no idea on how to approach this being pretty new to Java. This is supposed to be a beginner's homework so I suppose the method is very simple. Please show me how to do this and explain the steps if you can. Please and Thank you to whoever helps.
So your function should do something like this:
Determine number of padding characters required.
Need <= 0 padding characters? return input string
Otherwise, create a string with required padding characters, then return input string + required padding characters
You can find a string's length with the .length() method.
You could use the printf method in System.out (needs Java 1.6 or later, it's a new PrintStream method). Hake a look at an interesting example below, where the output is (specified below code). The padding is specified in the printf argument as 30, and is justified left:
package pft;
public class PrintfTest {
public static void main(String[] args) {
int padding = 30;
String s = "hi!";
System.out.printf("'%0$-" + padding + "s'", s);
}
}
prints: 'hi! '.
Taking it piece at a time (and without giving you all the code):
"Write a method called padString that
accepts two parameters: a String and
an integer representing a length."
public static ??? padString(String str, int len)
"For example,padString("hello", 8)
should return "hello"."
public static String padString(String str, int len)
{
throw new Error("not implemented yet");
}
"If the string's length is already at
least as long as the length parameter,
your method should return the original
string. For example,
padString("congratulations", 10)
should return "congratualtions"."
EDIT: you fixed the question...
public static String padString(String str, int len)
{
// if the str.length is greater than len
// return str
// this next part is very simple, not a very good way but gets you
// started. Once you have it working look at StringBuilder and .append.
// int val = the difference in length between the two strings
// for i = 0; i is less than val; i++
// str += " ";
// return str
}
public class PadString {
public static void main(String[] args) {
String str = "hello";
str = padStr(str, 10, ' ');
}
static String padStr(String s, int len, char c) {
int n = len - s.length();
if (n <= 0)
return s;
StringBuilder b = new StringBuilder(s);
for (int i = 0; i < n; i++)
b.append(c);
return b.toString();
}
}
Even thought this post is about 2 years old. I just recently had this
question for a homework. And I thought it might help other beginners
that might come across this problem to see a simpler way of solving
this problem.
One that will probably be more in line to where they are in their
beginner java course assuming they are getting this around the same
time that I did.
Of course you should remove the dashes in the loop and use spaces to
get credit for the assignment, that is there just to show you that it
works.
public class ex3_11_padString {
public static void main(String[] args) {
padString("hello",10);
}
public static String padString( String s, int len) {
int s_length = s.length();
int diff = len - s_length;
String newString;
newString = "";
for (int x = 0 ; x < diff; x++) {
newString += "-";
}
newString = newString + s;
return new String;
}
}
You may want to take a look at Java's String class documentation. Look for a method that returns the length of the string...
public static String padString(String str, int len)
{
int lengt=str.length();
if(lengt==len||lengt>len)
return str;
else if(lengt<len){
String spacstr="";
for(var i=lengt;i<len;i++){
spacstr+="$";
}
return str+spacstr;
}
}
///more generalized by accepting pad character
public static String padString(String str, int len,String padChar)
{
int lengt=str.length();
if(lengt==len||lengt>len)
return str;
else if(lengt<len){
String spacstr="";
for(var i=lengt;i<len;i++){
spacstr+=padChar;
}
return str+spacstr;
}
}
public String padString (String s, int padding) {
return String.format("%-" + padding + "s", s);
}
This is the better solution for me. Taken from the comment of #John C, with the "%-" added.
Sorry #John C I cannot edit your comment or add one below yours.