首页 > 解决方案 > 操作字符串以创建具有相应索引的新字符串

问题描述

输入:每天过得愉快

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() ;

输出:每天过得愉快

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

期望的输出:hae 和 via ecy

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

每天有安宁 => hae 和通过 ecy

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

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

标签: javastringbuilder

解决方案


使用简单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

推荐阅读