I need to get the space-separated tokens in a string, but I also need to know the character position within the original string at which each token starts. Is there any way to do this with StringTokenizer
. Also, as I understand it, this is a legacy class; is there a better alternative to using StringTokenizer
.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I improved micha's answer, so that it can handle neighboring spaces:
Output is:
You should always use
String#split()
to split your string rather thanStringTokenizer
.However, since you also want the position of the tokens in your string, then it would be better to use
Pattern
andMatcher
class. You have gotMatcher#start()
method which gives the position of the string matching the pattern.Here's an example: -
The pattern
\\S+
matches the non-space characters from that string. UsingMatcher#find()
methods returns all the matched substring.You can easily do this yourself using
String.split()
this prints: