Android 文字列の分割 質問する

Android 文字列の分割 質問する

という文字列がありCurrentString、次のような形式になっています"Fruit: they taste good"。を区切り文字として使用して を
分割したいと思います。そうすれば、単語は独自の文字列に分割され、別の文字列になります。そして、その文字列を表示するために、単に2 つの異なる を使用したいと思います。CurrentString:
"Fruit""they taste good"
SetText()TextViews

これに取り組む最善の方法は何でしょうか?

ベストアンサー1

String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

2 番目の文字列のスペースを削除することもできます。

separated[1] = separated[1].trim();

ドット(.)のような特殊文字で文字列を分割したい場合は、ドットの前にエスケープ文字\を使用する必要があります。

例:

String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"

他にも方法があります。たとえば、StringTokenizerクラス ( からjava.util) を使用できます。

StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method

おすすめ記事