简体   繁体   English

将Java字符从字符串拆分为字符串数组

[英]Java-Split characters from a String into an Array of Strings

    import java.io.*;

    public class Test{
       public static void main(String args[]){
          String Str = new String("Welcome to Tutorialspoint.com and again some other random stuff in this string.");
          String[] result= new String[8];
          byte c=0b0;
          int i=0;
          int j=0;

          for (int a=0;a<7;a++){
              result[a]="";
          }
          for(i=0; j<Str.length(); j++){
              c=(byte)(Str.charAt(j));  
              result [i]+=(char)c;
              if (i<7){i++;}else{i=0;}
          }
          for (int a=0;a<8;a++){
              System.out.println(result[a]);
          }
       }
    }

The goal is to create 8 strings from the original string. 目标是从原始字符串创建8个字符串。 String[0] will hold characters 0,8,16,...and so on. 字符串[0]将包含字符0、8、16等。 String[1] will hold characters 1,9,17,...and so on. String [1]将包含字符1,9,17等。 I hope this is clear enough. 我希望这足够清楚。

What I get with this code is something I cannot seem to overcome. 我用这段代码得到的东西似乎无法克服。

    Wtitdsemis
    eoa. or nt
    l lcam s r
    cTsogertti
    oupma auhn
    mto ionfig
    eoiantdfs.
    null rnn ho  

Notice null in last line - I need this gone as string should start with ' rnn ho' just like this. 注意最后一行为null-我需要这样做,因为字符串应以“ rnn ho”开头,就像这样。

    Wtitdsemis
    eoa. or nt
    l lcam s r
    cTsogertti
    oupma auhn
    mto ionfig
    eoiantdfs.
     rnn ho 

Would really appreciate if someone pointed out how to not get this output. 如果有人指出如何获取此输出,将不胜感激。 This is a 'test' code for splitting a String that will hold values from -126 to 127 binary. 这是一个“测试”代码,用于拆分一个字符串,该字符串将保存从-126到127的二进制值。 Not all of them will be printable and I need them to still be split correctly. 并非所有人都可以打印,我仍然需要正确分割它们。 For the most part code seems to work except for those seemingly random 'null' strings in output. 除了输出中那些看似随机的“ null”字符串外,大多数情况下代码似乎都可以工作。

I do not mind [null]=0 characters as long as they take 1 character space and not 4 in one String. 我不介意[null] = 0个字符,只要它们占用1个字符空间而不是4个字符串即可。

================================================================================== Initializing a<8 fixed this problem. ================================================== ================================初始化a <8解决了此问题。 But I did not even have time to read all other comments/answers. 但是我什至没有时间阅读所有其他评论/答案。 Did not expect such fast answers. 没想到这么快的答案。 THANK YOU ALL . 谢谢你们 。 I will up vote any relevant solution when I read them all and/or get reputation required. 阅读所有相关解决方案和/或获得所需声誉时,我将投票赞成任何相关解决方案。

================================================================================== FIXED!. ================================================== ==============================已修复!

================================================================================== Selected answer of Ian McLaird as not only it fixed my 'silly' mistake but also showed me neater code and functionality that I did not know about. ================================================== ===============================伊恩·麦克莱德(Ian McLaird)的选择答案,因为它不仅解决了我的“愚蠢”错误,而且还展示了我整理了我不知道的代码和功能。 Regardless thank you all for comments and answers. 无论如何,谢谢大家的评论和回答。

How about this? 这个怎么样?

public class StringSplitter {
    public static void main(String[] args) {
        String str = new String("Welcome to Tutorialspoint.com and again some other random stuff in this string.");
        String[] result = new String[8];

        for (int i = 0; i < result.length; ++i) {
            result[i] = "";
        }

        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; ++i) {
            result[i % result.length] += chars[i];
        }

        for (int i = 0; i < result.length; ++i) {
            System.out.println(result[i]);
        }
    }
}

Since your result array is already instantiated, it's safe to use the length property to initialize the elements to empty strings. 由于result数组已被实例化,因此使用length属性将元素初始化为空字符串是安全的。 Since you intend to process each character in the string, go ahead and just get it as an array, and then use the modulus operator to put each character into its proper place in the result array. 由于您打算处理字符串中的每个字符,因此继续将其作为数组获取,然后使用模运算符将每个字符放入result数组中的适当位置。 As an added benefit, it's also safe against changing the length of the result array. 另外一个好处是,它也可以安全地防止更改result数组的长度。 Hard-coded loop sentinels are dangerous. 硬编码的循环标记很危险。

Output 产量

Wtitdsemis
eoa. or nt
l lcam s r
cTsogertti
oupma auhn
mto ionfig
eoiantdfs.
 rnn ho  

From a quick glance at your code, the issue is that in your first for loop you're instantiating result[0] to result[6] and not instantiating result[7]. 快速浏览一下代码,问题在于在您的第一个for循环中,您正在实例化result [0]到result [6]而不是实例化result [7]。 When you put for (int a = 0; a <7; a++) the loop will run until a = 6 - when it gets increased to 7 a<7 returns false so after the first for loop, result[7]==null 当您输入for (int a = 0; a <7; a++) ,循环将运行直到a = 6-当它增加到7时,a <7返回false,因此在第一个for循环之后,result [7] == null

You can try the following: 您可以尝试以下方法:

import java.io.*;

public class Test{
  public static void main(String args[]){
    String Str = new String("Welcome to Tutorialspoint.com and again some other random stuff in this string.");

    String[] result = new String[8];

    for (int a = 0; a < result.length; a++)
       result[a] = "";

    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; ++i) 
      result[i % result.length] += chars[i];

    for (int a = 0; a < result.length; a++)
      System.out.println(result[a]);
  }
}

Resulting output will be: 结果输出将是:

Wtitdsemis
eoa. or nt
l lcam s r
cTsogertti
oupma auhn
mto ionfig
eoiantdfs.
 rnn ho

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM