【问题标题】:How to split a string into equal parts and store it in a string array如何将字符串分成相等的部分并将其存储在字符串数组中
【发布时间】:2020-02-08 06:27:13
【问题描述】:

我对 Java 还很陌生,并且被困在一个特定的家庭作业问题上,其中 String 获得通过,我必须从那里将其拆分为与通过的 Integer 相等的部分。

例如:输入字符串“HelloWorld”,它必须除以 2,然后必须将这些部分放入一个包含两个部分的数组中,例如:array[hello, world]。

有没有使用 FOR 循环来做到这一点?

到目前为止,我的代码将整个字符串输入到每个数组元素中。这是我的代码:

String[] splitIntoParts(String word, int size) {

    String[] array = new String[size];     

    for (int i = 0; i < array.length; i++) {
        array[i] = word;
        println(array[i]);;
    }

    return array;
}

【问题讨论】:

  • 使用子字符串。是否每个单词都分成长度相同的两部分?如果长度是偶数应该输出什么?
  • 你真的需要两个相等的部分吗?
  • 根据什么条件,你要拆分字符串?
  • @Renjith:根据代码,size 的每个尺寸应该有 n - 1 个部分,size 的尺寸应该多 1 个或更少。
  • 这个问题必须通过的另一个测试是一个 15 个字符长的字符串,我必须将它分成 3 个相等的字符串并将它们存储在一个数组中。

标签: java arrays


【解决方案1】:

有很多方法:

这是正则表达式版本:

public void splitEqual(String s){
        int length = s.length();//Get string length
        int whereToSplit;//store where will split

            if(length%2==0) whereToSplit = length/2;//if length number is pair then it'll split equal
            else whereToSplit = (length+1)/2;//else the first value will have one char more than the other

        System.out.println(Arrays.toString(s.split("(?<=\\G.{"+whereToSplit+"})")));//split the string

    }

\G 是一个零宽度断言,它匹配上一个匹配结束的位置。如果没有先前的匹配,则匹配输入的开头,与\A. 相同。封闭的lookbehind 匹配距离最后一个匹配结尾四个字符的位置。

lookbehind 和 \G 都是高级正则表达式功能,并非所有风格都支持。此外,\G 在支持它的各种风格中并没有一致地实现。这个技巧(例如)在 Java、Perl、.NET 和 JGSoft 中有效,但在 PHP (PCRE)、Ruby 1.9+ 或 TextMate(两者都是 Oniguruma)中无效。

使用子字符串:

/**
     * Split String using substring, you'll have to tell where to split
     * @param src String to split
     * @param len where to split
     * @return 
     */
    public static String[] split(String src, int len) {
        String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
        for (int i=0; i<result.length; i++)
            result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
        return result;
    }

您还应该检查这个答案:Google Guava split

【讨论】:

  • 这应该是公认的答案,因为它简洁、优雅、有据可查,并显示了 OP 中要求的适当功能(不像其他答案那样);换句话说:这是最好的答案。不过有一项改进:使用ceil(a/b) = (a + b - 1)/b 可以快速完成整数上限(@Rohit 也已经展示过)
【解决方案2】:

首先检查字符串的长度是否是除数的倍数:

if(str.length() % divisor == 0) 

然后你知道你可以抓住它的相等块。所以你使用substring 将它们拉出来,循环。

while(str.length() > 0) {
     String nextChunk = str.substring(0,divisor);
     // store the chunk. 

    str = str.substring(divisor,str.length());
} 

每次都会循环并抓取一个divisor 长的块。

【讨论】:

  • 你的回答是合理的
  • 对于我的问题,字符串总是可以被数字整除。
  • 您的答案是否将块存储在数组中?
  • @Nagash 我的回答怎么样?
  • @Nagash 你想存储在不同的数组中吗?或者只是一个没有意义的数组
【解决方案3】:

尝试以下应用程序。它根据提供的每个部分的大小将提供的单词分成相等的部分

public class WordSpliter {

  public static void main(String[] args) {
      String[] words = new WordSpliter().splitter("abcdefghij", 4);
      for(String s : words) System.out.println(s);
  }

  private String[] splitter(String word, int size) {
      // Decide the size of the String array 
      int rest = word.length() % size;
      int arrSize = ((word.length() - rest) / size) + 1;

      // Declare the array and the start point of the word
      String[] words = new String[arrSize];
      int startPoint = 0;

      for (int i = 0; i < words.length; i++) {
          if (i + 1 == words.length) {
              words[i] = word.substring(startPoint, startPoint + rest);
          } else {
              words[i] = word.substring(startPoint, startPoint +  4);
              startPoint += 4;
          }
      }
      return words;
  }

}

祝你好运!!!!

【讨论】:

    【解决方案4】:

    你可以使用蛮力

    public static List<String> splitStringEqually(String text, int size) 
    {
        List<String> result = new ArrayList<String>((text.length() + size - 1) / size);
        for (int i = 0; i < text.length(); i += size) {
            result.add(text.substring(i, Math.min(text.length(), i + size)));
        }
        return result;
    }
    

    【讨论】:

      【解决方案5】:
      String s = "HelloWorld";
      String firts_part=(String) s.subSequence(0, s.length() / 2);
      String second_part=(String) s.subSequence((s.length() / 2)+1,s.length()-1 );
      

      试试 subSequence();

      【讨论】:

        【解决方案6】:

        这不是抄袭,根据问题格式化此处提到的答案 - https://stackoverflow.com/a/3761521

        public static void main(String[] args){     
                String str = "HelloWorld";
        
                int parts = str.length()/3;
        
                System.out.println(Arrays.toString(
                        str.split("(?<=\\G.{"+parts+"})")
                    ));
        
            }
        

        【讨论】:

          【解决方案7】:

          因为字符串的长度减了 2

          代码

                  String st ="HelloWorld";
                  String firstPart = "";
                  String secondPart = "";
                  for (int j = 0; j < st.length(); j++) {
                      if ( j < st.length() /2) {
                          firstPart += st.charAt(j);
                      }else
                          secondPart += st.charAt(j);
                 }
          
                  System.out.println(firstPart);
                  System.out.println(secondPart);
          

          输出

          Hello
          World
          

          说明:只要你的索引不满足字符串的中间索引,你就添加到 firstPart 字符串。当它通过 String 的中间索引时,您制作 secondPart

          【讨论】:

          • 我宁愿不将 += 与字符串一起使用:它会重​​新创建 firstPartsecondPart 并且可能(对于大量输入)非常耗时。为什么不直接输入firstPart = st.substring(bla-bla-bla); secondPart = st.substring(some-other-bla-bla-bla);
          • @DmitryBychenko 感谢您的输入,但操作要求使用 for 循环
          • 我需要可以用于改变字符串长度和分割的代码。
          • @Nagash 但你说它可以被 2 整除?我对吗?这适用于那个
          【解决方案8】:

          仅查看您的输入 HelloWorld,您正试图将您的输入用大写字母作为子串。

          你应该这样做。

          String str = "HelloWorldUser";
          List<Integer> indexList = new ArrayList<>();
          for (int i = 0; i < str.length(); i++) {
              String temp = (str.charAt(i) + "").toUpperCase();
              if (temp.equals(str.charAt(i) + "")) { // check for upper case letters
                 indexList.add(i);
                }
           }
          List<String> subStrings = new LinkedList<>(); // to keep the insertion order
          for (int i = indexList.size() - 1; i > -1; i--) { // substring reverse order
               subStrings.add(str.substring(indexList.get(i)));
               str=str.substring(0,indexList.get(i));
           }
          Collections.reverse(subStrings); // reverse to get original order
          System.out.println(subStrings);
          

          输出:

          [Hello, World, User]
          

          如果您想将最终结果放入数组中,您可以使用

          String[] arr= subStrings.toArray(new String[subStrings.size()]);
          

          【讨论】:

            【解决方案9】:

            我想通了。这是我的代码:

                String[] array = new String[size];
                char[] charArray = new char[length(word)];
                char[] temp = new char[length(word) / size];
                int place = 0;
            
                // turn the string into an array of chars
                for (int i = 0; i < charArray.length; i++) {
                    charArray[i] = getChar(word, i);
                }
            
                // loop for each element of the desired string array
                for (int i = 0; i < array.length; i++) {
            
                    // fill a temp array with the correct characters and the corect amount of characters
                    for (int j = 0; j < charArray.length / size; j++) {                
                        temp[j] = charArray[place];
                        ++place;
                    }
            
                    // insert the temp array into each element of the string array
                    array[i] = new String(temp);
                }
            
                return array;
            

            【讨论】:

              【解决方案10】:

              一个简单的解决方案就像

               static void split(String str, int n) {
                  int partSize = str.length() / n;
                  while (str.length() - partSize > 0) {
                      String s = str.substring(0, partSize-1);
                      System.out.print(s + " ");
                      str = str.substring(partSize-1);
                  }
                  if (str.length() > 0) {
                      System.out.print(str);
                  }
              }
              

              【讨论】:

                【解决方案11】:

                您可以使用正则表达式如下:

                import java.util.Arrays;
                
                public class Main {
                    public static void main(String[] args) {
                        // Tests
                        System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 5)));
                        System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 4)));
                        System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 2)));
                    }
                
                    static String[] splitIntoParts(String word, int size) {
                        return word.replaceAll("(.{" + size + "})", "$1\n").split("\n");
                    }
                }
                

                输出:

                [Hello, World]
                [Hell, oWor, ld]
                [He, ll, oW, or, ld]
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-12-24
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2022-11-10
                  • 1970-01-01
                  相关资源
                  最近更新 更多