0

I am working on a simple program that needs to return 3 times a certain substring. For example, a call such as makeThreeSubstr("hello",0,2) should return "hehehe". I have the code ready to return "he", but I don't know an simple way to output the substring three times in a row. Any help is greatly appreciated.

class Main {
 public static String makeThreeSubstr (String word, int startIndex, int endIndex)
 {
  return (word.substring(startIndex, endIndex));

 }

 public static void main(String[] args){
    System.out.println(makeThreeSubstr("hello",0,2)); //should be hehehe
    System.out.println(makeThreeSubstr("shenanigans",3,7)); //should be naninaninani
  }
}

3 Answers3

4
String s = word.substring(startIndex, endIndex);
return s + s + s;
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27
  • This is definitely the answer I was looking for. For this specific problem, this solution works perfectly and is less cluttered than a loop. – Omar Zarbostic Apr 21 '17 at 02:26
  • Have a look at the link to the duplicate marked answer too. It has a similar question and users have explained it in a lot of different ways to do it. – Devendra Lattu Apr 21 '17 at 02:37
0

Based on this answer Simple way to repeat a String in java

String  repeated = new String(new char[3]).replace("\0", word.substring(startIndex, endIndex));
return repeated;
Community
  • 1
  • 1
Ray
  • 3,864
  • 7
  • 24
  • 36
  • To whoever downvoted my answer: it would be helpful if you at least explained why. We're all just trying to learn. – Ray Apr 21 '17 at 03:26
0

The quick and dirty way to do it is:

public static String makeThreeSubstr (String word, int startIndex, int endIndex)
{
  String substring = word.substring(startIndex, endIndex);
  return substring + substring + substring;
}
Joey deVilla
  • 8,403
  • 2
  • 29
  • 15