文字列内のスペースで区切られたトークンを取得する必要がありますが、各トークンが始まる元の文字列内の文字位置も知る必要があります。でこれを行う方法はありますかStringTokenizer
。また、私が理解しているように、これはレガシー クラスです。を使用するより良い代替手段はありますかStringTokenizer
。
5723 次
3 に答える
8
String#split()
ではなく、常に文字列を分割するために使用する必要がありますStringTokenizer
。
ただし、文字列内のトークンの位置も必要なので、Pattern
andMatcher
クラスを使用する方がよいでしょう。Matcher#start()
パターンに一致する文字列の位置を与えるメソッドがあります。
以下に例を示します: -
String str = "abc asf basdfasf asf";
Matcher matcher = Pattern.compile("\\S+").matcher(str);
while (matcher.find()) {
System.out.println(matcher.start() + ":" + matcher.group());
}
パターン\\S+
は、その文字列のスペース以外の文字と一致します。Matcher#find()
メソッドを使用すると、一致したすべての部分文字列が返されます。
于 2012-12-23T11:26:28.503 に答える
1
これを自分で簡単に行うことができますString.split()
String text = "hello world example";
int tokenStartIndex = 0;
for (String token : text.split(" ")) {
System.out.println("token: " + token + ", tokenStartIndex: " + tokenStartIndex);
tokenStartIndex += token.length() + 1; // +1 because of whitespace
}
これは次のように表示されます:
token: hello, tokenStartIndex: 0
token: world, tokenStartIndex: 6
token: example, tokenStartIndex: 12
于 2012-12-23T11:28:26.123 に答える
0
隣接するスペースを処理できるように、micha の回答を改善しました。
String text = "hello world example";
int start = 0;
for (String token : text.split("[\u00A0 \n]")) {
if (token.length() > 0) {
start = text.indexOf(token, start);
System.out.println("token: " + token + ", start at: " + start);
}
}
出力は次のとおりです。
token: hello, start at: 0
token: world, start at: 7
token: example, start at: 17
于 2016-04-05T13:06:44.093 に答える