我试图在数组中循环字符串列表每个字母的两倍。
例如:[ “ABC”, “DEF”] - > [ “为aabbcc”, “ddeeff”]
ArrayList<String> aa;
aa = new ArrayList<String>();
String res = "";
for(int i=0;i<words.size();i++){
char at = aa.get(i);
res=res+at+at;
}
return res;
我还是新的编码,你可以看到,我的代码是一个烂摊子。帮助表示赞赏。提前致谢
您一些问题,您的实现:
words
阵列互动,但使用的价格指数比aa
。由于这是从来没有添加的项目给它,你会得到一个ArrayIndexOutOfBoundsException
。return res
但这只会返回一个字符串,而不是单词的数组。根据你的例子这是可以做到这样:
public static ArrayList<String> doubleWords(ArrayList<String> input) {
ArrayList<String> result = new ArrayList<>();
for (String string : input) {
String word = "";
for (int i = 0; i < string.length(); i++) {
word += ""+string.charAt(i)+string.charAt(i);
}
result.add(word);
}
return result;
}
你与ArrayList
的[abc, def]
输出将[aabbcc, ddeeff]
。
你需要通过字符字符串中通过你的单词列表进行迭代,然后在列表中迭代每一个字,就像这样:
public ArrayList<String> doubleWords(ArrayList<String> words) {
ArrayList<String> doubledWords = new ArrayList<String>();
for (String word : words) {
String newWord = "";
for (int i=0; i<word.length(); i++) {
newWord = newWord + word.substring(i, i+1) + word.substring(i, i+1);
}
doubledWords.add(newWord);
}
return doubledWords;
}
由于Java 8这也可以通过以下方式来实现:
String input = "abc";
StringBuilder builder = new StringBuilder();
input.chars().forEach(value -> builder.append((char)value).append((char)value));
Remeber到int
价值,你追加之前转换回char
。
用于上述程序的输出:
System.out.println(builder.toString());
// aabbcc
//response list
ArrayList<String> aa;
aa = new ArrayList<String>();
StringBuilder sb = new StringBuilder() ;
String word;
// iterate list of words
for(int i=0; i < words.size(); i++){
//get word
word = words.get(i);
//iterate each character in word
for(int j =0; j < words; j++) {
//append each char twice in StringBuilder
sb.append(word[j).append(word[j]);
}
//add word to output list
aa.add(sb.toString());
//empty StringBuilder for next word
sb.setLength(0);
}
return aa;
它只能通过Java流API来完成,没有任何临时变量:
List<String> result = listOfWords.stream().
map(value -> String.valueOf( // new result String(doubled word)
value.chars() // get chars for each original string
.mapToObj(i-> (char)i) // cast each char from int to char type
.map(c -> String.valueOf(new char[]{c, c})) // create doubled char string
.collect(Collectors.joining()))) // concatenate all doubled chars
.collect(Collectors.toList()); // collect result to list