JellybeanNewbie:
私は、文字列の最後の言葉を返すメソッドを作成しようとしているが、私はいくつかの問題、それを書いを持っています。
私は、文字列の最後の空白を見つけ、単語を見つけるために、部分文字列を使用してそれを実行しようとしています。これは私がこれまで持っているものです。
String strSpace=" ";
int Temp; //the index of the last space
for(int i=str.length()-1; i>0; i--){
if(strSpace.indexOf(str.charAt(i))>=0){
//some code in between that I not sure how to write
}
}
}
私は、言語の複雑な部分の多くを知らないので、私はJavaで始めています。誰かがこの問題を解決するための簡単な方法を見つける私を助けることができれば、それははるかに高く評価されるだろう。ありがとう!
憲兵:
String#lastIndexOf
そしてString#substring
あなたの友人はここにあります。
char
Javaでsが直接に変換することができint
、我々は最後のスペースを見つけるために使用します秒、。その後、我々は単に、そこから部分でしょう。
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));
これは、あまりにもスペース文字自体を出力します。それを取り除くために、私達はちょうど私たちが1でサブストリング位置のインデックスをインクリメントします。
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));
あなたが使用したくない場合はString#lastIndexOf
、あなたが任意の左を持っていないまで、あなたは文字列をループし、すべてのスペースでそれをサブストリングすることができます。
String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);