我正在研究一个需要返回某个子字符串3次的简单程序。例如,诸如makeThreeSubstr(" hello",0,2)之类的调用应返回" hehehe"。我已准备好返回代码"他",但我不知道连续三次输出子字符串的简单方法。非常感谢任何帮助。
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
}
}
答案 0 :(得分:4)
String s = word.substring(startIndex, endIndex);
return s + s + s;
答案 1 :(得分:0)
根据这个答案Simple way to repeat a String in java
String repeated = new String(new char[3]).replace("\0", word.substring(startIndex, endIndex));
return repeated;
答案 2 :(得分:0)
快速而肮脏的方法是:
public static String makeThreeSubstr (String word, int startIndex, int endIndex)
{
String substring = word.substring(startIndex, endIndex);
return substring + substring + substring;
}