操纵字符串以使用各自的索引创建新字符串

manipulating the strings to make new strings with the respective indexes

input :have anic eday

String[] words = sb.toString().split("//s");
    StringBuilder sbFinal = new StringBuilder();

    for(int i=0;i<words[0].length() ;i++){
        for(int j=0;j<words.length;j++){
            sbFinal.append(words[j].charAt(i));
        }
    }

    return sbFinal.toString() ;

output : have anic eday

我有一些字符串需要转换为打印一组新字符串(space 分隔)的形式,这些字符串由给定的每个字符串的相应字符组成。

desired output : hae and via ecy

例如我们有 3 个单词,每个单词有 4 个字符,我们想要 4 个单词,每个单词有 3 个字符。

have anic eday =>hae 和 via ecy

我们从所有 3 个单词中选择第一个字符来构成新的第一个单词。

我使用了上面显示的代码,但它本身将输入打印为输出。

使用简单的 for 循环和数组:

public class SO {

    public static void main(String args[]) {
        String input = "have anic eday ";

        // Split the input.
        String[] words = input.split("\s");
        int numberOfWords = words.length;
        int wordLength = words[0].length();

        // Prepare the result;
        String[] result = new String[wordLength];

        // Loop over the new words.
        for (int i = 0; i < wordLength; i++) {
            // Loop over the characters in each new word.
            for (int j = 0; j < numberOfWords; j++) {
                // Initialize the new word, if necessary.
                String word = result[i] != null ? result[i] : "";

                // Append the next character to the new word.
                String newChar = Character.toString(words[j].charAt(i));
                result[i] = word + newChar;
            }
        }

        for (String newWord : result) {
            System.out.println(newWord);
        }
    }
}

输出:

hae
and
via
ecy

虽然回答了,但我制作了一个与您最初设计的版本更相似的版本,只是使用 sysout 而不是 return,但是根据您的需要进行更改,或者只调整 .split() 行:

String sb = "have anic eday";
String[] words = sb.split("\s"); //you need to use BACKWARDSLASH "\s" to get it to work.
StringBuilder sbFinal = new StringBuilder();


for (int i = 0; i < words[0].length(); i++) {
    for (int j = 0; j < words.length; j++) {
        sbFinal.append(words[j].charAt(i));
    }
    sbFinal.append(" ");
}

System.out.println(sbFinal.toString());

您用“//s”拆分,但是“”或“\\s”似乎工作得很好。