猿问

操作字符串以创建具有相应索引的新字符串

输入 :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() ;

输出 : have anic eday


我有许多字符串,我需要将它们转换为打印一组新字符串(空格分隔)的形式,这些字符串由给定的每个字符串的各自字符形成。


所需的输出:hae 和 via ecy


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


have anic eday =>hae and via ecy


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


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


撒科打诨
浏览 137回答 2
2回答

UYOU

虽然得到了回答,但我编写了一个与您最初设计的更相似的版本,只是使用 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++) {&nbsp; &nbsp; for (int j = 0; j < words.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; sbFinal.append(words[j].charAt(i));&nbsp; &nbsp; }&nbsp; &nbsp; sbFinal.append(" ");}System.out.println(sbFinal.toString());你用“//s”分割,但是“”或“\\s”似乎工作得很好。

蛊毒传说

使用简单的for循环和数组:public class SO {&nbsp; &nbsp; public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp; String input = "have anic eday ";&nbsp; &nbsp; &nbsp; &nbsp; // Split the input.&nbsp; &nbsp; &nbsp; &nbsp; String[] words = input.split("\\s");&nbsp; &nbsp; &nbsp; &nbsp; int numberOfWords = words.length;&nbsp; &nbsp; &nbsp; &nbsp; int wordLength = words[0].length();&nbsp; &nbsp; &nbsp; &nbsp; // Prepare the result;&nbsp; &nbsp; &nbsp; &nbsp; String[] result = new String[wordLength];&nbsp; &nbsp; &nbsp; &nbsp; // Loop over the new words.&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < wordLength; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Loop over the characters in each new word.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j < numberOfWords; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Initialize the new word, if necessary.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String word = result[i] != null ? result[i] : "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Append the next character to the new word.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String newChar = Character.toString(words[j].charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[i] = word + newChar;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for (String newWord : result) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(newWord);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}输出:haeandviaecy
随时随地看视频慕课网APP

相关分类

Python
我要回答