2016-11-17 121 views
0

這是用於我的修訂。我試圖通過重複String s來建立一串int n字符。我試圖得到的答案是testtestte通過重複字符串打印「n」個字符的字符串

這是我到目前爲止。當索引達到4時,由於字符串只有4個字符,它顯然會出局或綁定。我希望它能夠在索引達到3時回到0並繼續,直到int n滿足爲止(這可能是錯誤的詞)10.如果問題不夠清楚,對不起。

public static void main(String[] args){ 

    beads("test", 10); 

    } 

public static void beads(String s, int n){ 

    char[] eachChar = new char[n]; 
    for (int index = 0; index < n; index++) { 
     eachChar[index] = s.charAt(index); 
    } 
    System.out.println(eachChar); 

    } 

回答

3

一個簡單的解決方案是通過字符串的長度,以模指數:

eachChar[index] = s.charAt(index % s.length()); 
2

只需使用MOD(%)運算符。

public static void main(String[] args){ 
    beads("test", 10); 
} 

public static void beads(String s, int n){ 
    char[] eachChar = new char[n]; 
    for (int index = 0; index < n; index++) { 
     eachChar[index] = s.charAt(index%s.length()); 
    } 
    System.out.println(eachChar); 
} 
2

考慮的方式更容易和懶惰的方式

String in = "test"; 
    int len = 10; 

    StringBuilder buf = new StringBuilder(); 
    while (buf.length() < len) { 
     buf.append(in); 
    } 
    System.out.println(buf.substring(0, len)); 

總是試圖找到一個更簡單的方式做事情到底會有更少的錯誤

0

去最快的方法是使用arrayCopy,將值複製到數組中。這與「string/stringbuilder etc ..」在內部使用的方法相同 下面是如何使用它

public static void main(String[] args) { 
      timesRepeat("test",30); 
     } 
     public static void timesRepeat(String input , int times) 
     { 
      char[] resultString = new char[times]; 
      //write in bouts 

      int fullPart = times/input.length(); 
      int partPart = times%input.length(); 
      for (int i =0 ; i< fullPart; i++) 
      { 
       System.arraycopy(input.toCharArray(), 0, resultString, (i*input.length()), input.length()); 
      } 

      System.arraycopy(input.toCharArray(), 0, resultString, (fullPart)*input.length(), partPart); 
      System.out.println(resultString); 
     }