Development/CodeWorkout

[CodeWorkout] X121: extraEnd

bbubbush 2022. 4. 26. 00:10

Question

Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string's length will be at least 2.

 

Answer

반응형
public class X121 {
  public static void main(String[] args) {
    String str = "";

    str = "Hello";
    System.out.printf("[str = %s]\n", str);
    System.out.println(extraEnd(str));
    str = "Hi";
    System.out.printf("[str = %s]\n", str);
    System.out.println(extraEnd(str));
    str = "Candy";
    System.out.printf("[str = %s]\n", str);
    System.out.println(extraEnd(str));
  }

  public static String extraEnd(String str) {
    String result = "";
    for (int i = 0; i < 3; i++) {
      result += str.substring(str.length() - 2);
    }
    return result;
  }
}

 

Use the String.repeat() method provided by JDK11

public class X121 {
  public static void main(String[] args) {
    String str = "";

    str = "Hello";
    System.out.printf("[str = %s]\n", str);
    System.out.println(extraEnd(str));
    str = "Hi";
    System.out.printf("[str = %s]\n", str);
    System.out.println(extraEnd(str));
    str = "Candy";
    System.out.printf("[str = %s]\n", str);
    System.out.println(extraEnd(str));
  }

  public static String extraEnd(String str) {
    return str.substring(str.length() - 2).repeat(3);
  }
}

 

Ref

https://github.com/bbubbush/codeworkout/blob/master/src/com/bbubbush/tistory/X121.java

 

GitHub - bbubbush/codeworkout

Contribute to bbubbush/codeworkout development by creating an account on GitHub.

github.com

 

'Development > CodeWorkout' 카테고리의 다른 글

[CodeWorkout] X323: sumRange  (0) 2022.05.06
[CodeWorkout] X158: bunnyEars2  (0) 2022.05.05
[CodeWorkout] X119: squareUp  (0) 2022.04.27
[CodeWorkout] X125: repeatSeparator  (0) 2022.04.25