【问题标题】:Printing a string of 'n' characters by repeating a string通过重复一个字符串来打印一个由“n”个字符组成的字符串
【发布时间】:2017-03-31 14:32:13
【问题描述】:

这是我的修改。我正在尝试通过重复 String s 来构建一串 int n 字符。我想要得到的答案是testtestte

这是我目前所拥有的。当索引达到 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);

  }

【问题讨论】:

    标签: java string loops int


    【解决方案1】:

    最快的方法是使用 arrayCopy ,将值复制到 bouts 中的数组。这与“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);
            }
    

    【讨论】:

      【解决方案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));
      

      总是尝试找到一种更简单的方法来做事,因为最终会有更少的错误

      【讨论】:

        【解决方案3】:

        只需使用 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);
        }
        

        【讨论】:

          【解决方案4】:

          一个简单的解决方案是用字符串的长度对索引取模:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-04-10
            • 2020-02-28
            • 2021-12-09
            • 1970-01-01
            • 2017-11-23
            • 1970-01-01
            • 2019-02-19
            • 2021-10-04
            相关资源
            最近更新 更多