Java 如何替换字符串中的某些单词?
回答前请注意:不要说我可以使用正则表达式、拆分、替换。。。因为我知道,我需要这样做 在下面的代码中,我试图将“for”替换为4,“to&”,“you”替换为U,“to”替换为2。我必须解决这个问题。一个是,我不知道如何创建一个字符串对象,它总是允许我添加自己,也就是说,在我前进的过程中添加更多的单词。第二个问题是变量“space”(查找索引“”)在第一次运行代码后等于0,我不明白为什么 代码:Java 如何替换字符串中的某些单词?,java,string,recursion,Java,String,Recursion,回答前请注意:不要说我可以使用正则表达式、拆分、替换。。。因为我知道,我需要这样做 在下面的代码中,我试图将“for”替换为4,“to&”,“you”替换为U,“to”替换为2。我必须解决这个问题。一个是,我不知道如何创建一个字符串对象,它总是允许我添加自己,也就是说,在我前进的过程中添加更多的单词。第二个问题是变量“space”(查找索引“”)在第一次运行代码后等于0,我不明白为什么 代码: public static void shorthand(String sentence){
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
在第一次运行代码之后
//如果我把字符串完全插入;它说变量可能不是
已初始化,不允许我运行
这是因为您需要给它一个初始值,例如:
String completeSentence = "";
但是,在这种情况下,使用
StringBuilder
可能更可取(即使编译器可能会尝试简单地优化当前策略)为什么不能使用正则表达式、拆分或替换?使用StringBuffer
。如果坚持使用字符串,请在循环外部声明completeSentence,如下所示:String completeSentence=“”代码>@KatjaChristiansen因为我的老师说我们cant@Arkadiy您的意思是:publicstaticvoidshorthand(字符串句子){stringcompletestentence=“”;…}
Yes。只要把它放在你有一个评论说你有编译器错误的地方。好吧,但我仍然得到一个StackOverFlow错误。由于某种原因,在我第一次运行代码之后,它不会改变它的值。等等,我很困惑。你为什么要递归地这样做?这是要求的一部分吗?如果在循环外部维护StringBuilder
,然后将原始字符串分成块(使用indexOf
),请执行检查,然后在循环外部附加到StringBuilder
。