切换 for 和 foreach

我需要在此方法中将 for 循环更改为 foreach 循环,我该怎么做?(如有需要,可以添加全班)


public String decode(String input) {

    String[] letters = input.split(" ");

    StringBuilder ret = new StringBuilder();


    for(int i=0; i<letters.length; i++)

        ret.append(decodeMap.get(letters[i]));

    return ret.toString();

}


杨__羊羊
浏览 79回答 2
2回答

慕雪6442864

您应该指定您正在使用哪种语言。我假设是java. 使用for(datatype var : collection). 这是它的样子public String decode(String input) {&nbsp; &nbsp; String[] letters = input.split(" ");&nbsp; &nbsp; StringBuilder ret = new StringBuilder();&nbsp; &nbsp; for(String s : letters){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ret.append(decodeMap.get(s));&nbsp; &nbsp; }&nbsp; &nbsp; return ret.toString();}

慕妹3242003

为了避免不必要的创建,StringBuilder我建议类似的操作(假设您使用的是 Java 8+):&nbsp; &nbsp; public String decode(String input) {&nbsp; &nbsp; &nbsp; &nbsp; String[] letters = input.split(" ");&nbsp; &nbsp; &nbsp; &nbsp; return Arrays.stream(letters)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(decodeMap::get)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.joining());&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java