java - 操作字符串以创建具有相应索引的新字符串
问题描述
输入:每天过得愉快
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 个单词中选择第一个字符来制作新的第一个单词。
我使用了上面显示的代码,但它将输入打印为输出本身。
解决方案
使用简单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
推荐阅读
- java - 使用@sql spring boot test从资源文件夹以外的自定义位置读取.sql文件
- sql-server - asp.net core code first 无法打开登录请求的数据库“DbName”。登录失败
- javascript - jquery按钮箭头功能
- apache - Apache 重写 XSS 保护问题
- python - 不止一次在 Apache Flink 中计算时间属性
- html - 绘制后订购 svg 元素
- node.js - “无法保存连接器配置。请重试”错误
- javascript - NodeJS + ExpressJS:如何等待 forEach 完成内部的 SQL 查询
- javascript - Angular 购物车应用程序 - 页面需要刷新,DOM 才能接受更改
- asp.net-core - 如何使用 IApplicationBuilder 的 ApplicationServices