1

I stuck a little. I have a method, which should return a new String contains X times repeated character "y". X and Y are arguments of method. So, simple solution wiil be like this:

public String someMethod(int x,char y){
    String result="";
    for (int i=0;i<x;i++) result+=y;
    return result;    
}

And I've tried to figure out, is there any way to do the same just in one line, without looping. For example:

public String someMethod(int x,char y){
    return new StringBuilder().append('y', x);    
}

But there isn't such method for StringBuilder or StringBuffer or etc. Can you give me any suggestions? Thanks in advance.

Updated: So, the solution will be:

public String someMethod(int x,char y){
    return new String(new char[x]).replace("\0", String.valueOf(y))  
}

Thanks for help!

4
  • 1
    Any reason why it has to be done without a loop? Any built-in function, if it were to exist, most likely uses a loop anyway. Commented Apr 18, 2014 at 7:50
  • Just for simplifying (making code more compact). Commented Apr 18, 2014 at 7:58
  • 1
    Not a good reason, use loop instead. Commented Apr 18, 2014 at 7:59
  • 1
    If I would look at your code, I would start thinking like "what is s/he trying to achieve", soon followed by "Why no loop? There must be a reason for it". If you would just use a loop (while avoiding concatenation - use StringBuilder), it's obvious what you are trying to do, and it's the usual way. Commented Apr 18, 2014 at 8:05

7 Answers 7

1

Try this. Here we are generating a new char[] which default initializes to all 0's, and then replacing these 0's with the character we want.

public class B {

    public static void main(String[] args) {            
        int x = 5;
        String y = "h";
        String result = new String(new char[x]).replace("\0", y);
        System.out.println(result);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@user3523579, I just updated it to use a variable instead of a literal, but it's the same thing.
There is more simple than that: create a char[] and use Arrays.fill()
@fge, Arrays.fill() returns void so that would require at least three lines (one to declare the char[], one to fill it, and one to make a string out of it), where my solution requires one line.
1

You can do

import java.util.Arrays;

public String someMethod(int x,char y){
    char[] a = new char[x];
    Arrays.fill(a, 0, x, y);
    return new String(a);
}

Comments

1

As others are saying, it's not possible completely without a loop - you could hide it behind other methods, but they still use a loop.

If it's just for the sake of "more compact" code, you could write your own method to do exactly that - or you use third party libs like Apache Commons StringUtils : StringUtils.repeat(String str, int repeat) should do the job

Javadoc for StringUtils.repeat(...)

Comments

1

Answering my own question almost 5 years later.

In Java 11 it can be done as following:

public String someMethod(int x, char y) {
    return String.valueOf(y).repeat(x);
}

Comments

0

Use StringBuffer & loop, without loop this can't be done.
Even you found a method that could do it without loop, inside it's still use loop.

Comments

0
public String someMethod(int x,char y) {
    StringBuilder buff = new StringBuilder();
    return someMethod( x, y, buff );
}

public String someMethod(int x,char y, StringBuilder buff) {
    if (x == 0) return buff.toString();
    else {
        buff.append( y );
        return someMethod( x, y, buff );
    }
}

...but recursion is not better than loop if this is not a puzzle...

On the other hand, recursion is more general, when someone wants to remove loop comparing to some String realted functions (in this case new String(char[]) and replace())

Comments

0

For java 8 you could use a stream:

Stream.generate(() -> String.valueOf(y))
      .limit(x)
      .collect(Collectors.joining()).toString()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.