猿问

如何在 Java 中使用 split() 字符串方法分隔单词

我想分隔单词并将它们打印在一行中,中间有一个连字符(-)。我编写了以下代码,但它只打印最后一个单词,后跟一个连字符,即输出是胡萝卜-。我不明白为什么以及我要进行哪些更改才能获得所需的输出?


public class SeparatingWords {


    public static void main(String[] args) {

        String str = "apple banana carrot";

        System.out.println(separatingWords(str));

    }


    public static String separatingWords(String str) {

        String[] words = str.split(" ");

        String result = null;


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

            result=words[i]+"-";

        }


        return result;

    }

}


潇潇雨雨
浏览 251回答 3
3回答

呼唤远方

而不是调用 asplit并连接字符串,为什么不能直接调用replaceAll以实现您的目标。这将使您的代码变得简单。String result = str.replaceAll(" ", "-");以下是您的示例修改代码。希望这可以帮助public class Sample {public static void main(String[] args) {&nbsp; &nbsp; String str = "apple banana carrot";&nbsp; &nbsp; System.out.println(separatingWords(str));&nbsp;}public static String separatingWords(String str) {&nbsp; &nbsp; String result = str.replaceAll(" ", "-");&nbsp; &nbsp; return result;&nbsp;}}如果您想根据方法内部的要求执行任何其他操作,那么下面应该适合您。正如@Moler 所建议的那样,添加+=并初始化了result对象public static String separatingWords(String str) {&nbsp; &nbsp; String[] words = str.split(" ");&nbsp; &nbsp; String result = "";&nbsp; // Defaulted the result&nbsp; &nbsp; for (int i = 0; i < words.length-1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; result += words[i] + "-";&nbsp; // Added a +=&nbsp; &nbsp; }&nbsp; &nbsp; result += words[words.length - 1];&nbsp; &nbsp; return result;}
随时随地看视频慕课网APP

相关分类

Java
我要回答