如何替换String中的某些单词?

时间:2013-11-05 20:15:46

标签: java string recursion

在回答之前注意:不要说我可以使用正则表达式,拆分,替换...因为我知道,我需要以这种方式专门做。

我有以下代码,其中我尝试将“for”替换为4,“和”替换为&,将“you”替换为U,将“to”替换为2.我不得不将此问题替换为问题。一个是我不知道如何创建一个String对象,它总是允许我添加自己,即在我去的时候添加更多的单词。第二个问题是变量“space”(找到indexOf“”)在第一次运行代码后等于0,我不明白为什么。

代码:

    public static void shorthand(String sentence){
    //if I put String completeSentence; it says the variable might not have been initialized and wont let me run. 

    if (sentence.length() > 0){
        int space = sentence.indexOf(" ");
        String completeSentence = ""; //however if I put this here I just reset my value all the time and cant see the full string after it all adds up.
        if (space == -1){
            if (sentence.equalsIgnoreCase("to")){
                completeSentence += "to";
            } else if(sentence.equalsIgnoreCase("for")){
                completeSentence += "4";
            } else if (sentence.equalsIgnoreCase("you")){
                completeSentence += "you";
            } else if(sentence.equalsIgnoreCase("and")){
                completeSentence += "&";
            } else {
                completeSentence += sentence;
            }
            System.out.println(completeSentence);
        } else {
            String word = sentence.substring(0,space);
            if (word.equalsIgnoreCase("to")){
                completeSentence += "to";
            } else if(word.equalsIgnoreCase("for")){
                completeSentence += "4";
            } else if (word.equalsIgnoreCase("you")){
                completeSentence += "you";
            } else if(word.equalsIgnoreCase("and")){
                completeSentence += "&";
            } else {
                completeSentence += word;
            }
            shorthand(sentence.substring(space));
        }
    }
}  

主要:

public class Main {
public static void main (String [] args){
    Scanner in = new Scanner(System.in);
    String word = in.nextLine();
    Functions.shorthand(word);
}
}

我可以做什么来添加相同的字符串,所以到最后我可以看到我的完整句子?还有为什么我的space = 0在第一次运行代码之后呢?

1 个答案:

答案 0 :(得分:0)

  

//如果我把String completeSentence;它说变量可能不会   已经初始化,不会让我跑。

那是因为你需要给它一个初始值,例如:

String completeSentence = "";

但是,在这种情况下使用StringBuilder可能更好(即使编译器可能会尝试优化您当前的策略)