【问题标题】:How do I split a string into even parts then populate an array with those new strings?如何将字符串拆分为偶数部分,然后用这些新字符串填充数组?
【发布时间】:2016-06-04 18:52:08
【问题描述】:

我正在开发一个程序,我将要求用户输入一个没有空格的完整字符字符串。然后我将把这个字符串分成三个字符的部分,我想用这些三个字符的新字符串填充一个数组。所以基本上我要问的是我将如何创建一个方法来获取输入字符串,将其分成三个单独的部分,然后用它填充一个数组。

while (i <= DNAstrand.length()-3) {
DNAstrand.substring(i,i+=3));
}

这段代码会将字符串分成三部分,但是如何将这些值分配给方法中的数组?

感谢任何帮助!

【问题讨论】:

    标签: java arrays split


    【解决方案1】:

    循环并将所有输入添加到数组中。

        String in = "Some input";
    
        //in.length()/3 is automatically floored
        String[] out = new String[in.length()/3];
    
        int i=0;
    
        while (i<in.length()-3) {
            out[i/3] = in.substring(i, i+=3);
        }
    

    如果字符串的长度不是 3 的倍数,这将忽略字符串的结尾。结尾可以通过以下方式找到:

    String remainder = in.substring(i, in.length());
    

    最后,如果你想让余数成为数组的一部分:

        String in = "Some input";
    
        //This is the same as ceiling in.length()/3
        String[] out = new String[(in.length()-1)/3 + 1];
    
        int i=0;
    
        while (i<in.length()-3) {
            out[i/3] = in.substring(i, i+=3);
        }
        out[out.length-1] = in.substring(i, in.length());
    

    【讨论】:

      【解决方案2】:

      试试这个:

      private static ArrayList<String> splitText(String text)
      {
          ArrayList<String> arr = new ArrayList<String>();
          String temp = "";
          int count = 0;
          for(int i = 0; i < text.length(); i++)
          {
              if(count < 3)
              {
                  temp += String.valueOf(text.charAt(i)); 
                  count++;
                  if(count == 3)
                  {
                      arr.add(temp);
                      temp = "";
                      count = 0;
                  }
              }
      
          }
          if(temp.length() < 3)arr.add(temp);//in case the string is not evenly divided by 3
          return arr;
      }
      

      你可以这样调用这个方法:

      ArrayList<Strings> arrList = splitText(and the string you want to split);
      

      【讨论】:

      • 如何将我的字符串从 main 传递给这个方法?我相信您的解决方案会起作用我只是在这样做时遇到了麻烦。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      相关资源
      最近更新 更多