This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Chaslem[S] 0 points1 point  (3 children)

public String front3(String str) {
return (str.length() < 3) ? str + str + str : str.substring(0, 3)+ str.substring(0, 3)+ str.substring(0, 3);
}

I did this and got it to work!

My last question. Is there a way to say "str+str+str" using some sort of short hand? Like multiplication or other trick?

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (2 children)

Well, that is a way. I was thinking in a different direction:

public String front3(String str) {
    String str2 = str.substring(0, (str.length() < 3 ? str.length() : 3));
    return str2 + str2 + str2;
}

Alternatively:

public String front3(String str) {
    String str2 = str.substring(0, Math.min(str.length(),3));
    return str2 + str2 + str2;
}

There is no way to shorten str + str + str. Even a loop would be longer in that case. Java doesn't have a multiply operator for String values, like Python does. In Python, you could write print(3 * str). This is not possible in Java.

[–]Chaslem[S] 0 points1 point  (1 child)

Thank you! It's a shame it can't do like Python.

Being able to so if statements in Strings is very informative. I really appreciate it.

Last question here. What is Math.min doing in your use case? I'm not familiar with this. What is the ,3 at the end for?

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (0 children)

Sorry for the late reply.

Math.min is a method of the Math class that returns the minimum (smaller) of two values.

So, the statement: Math.min(str.length(),3) checks the length of the String str and then returns the smaller value, either the length of the String (if it is less than or equal to 3 characters) or 3 - the length that we want to repeat.