答える前に注意してください:正規表現、分割、置換を使用できるとは言わないでください...私はそれを知っているので、具体的にこの方法で行う必要があります。
次のコードでは、「for」を 4 に、「and」を & に、「you」を U に、「to」を 2 に置き換えようとしています。これには問題があります。1 つは、いつでも自分自身に追加できるようにする String オブジェクトを作成する方法がわからないことです。つまり、さらに単語を追加することができます。そして 2 番目の問題は、変数 "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
、コードを最初に実行した後はなぜですか?