2 回答
TA贡献1878条经验 获得超4个赞
虽然得到了回答,但我编写了一个与您最初设计的更相似的版本,只是使用 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”似乎工作得很好。
TA贡献1895条经验 获得超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
添加回答
举报