user6923858
user6923858

Reputation:

How To Get The Position of A Substring

I'm trying to get the position of multiple substrings in my string. I'm using a tokenizer to go through the words in the string if that may be of importance.

For example, if my input was:

"Hello < shaz = 2"

I would like to get the position of each element such that

Hello : Pos 1
< : Pos 7
shaz : Pos 9
= : Pos 14
2 : Pos 16

I've tried using the following as an example:

String string = "Hello, my name is";
System.out.println(string.indexOf("my") + 1);

This printed 8, as I wished but I would like to get the position of every substring.

Upvotes: 1

Views: 622

Answers (2)

jwitt98
jwitt98

Reputation: 1255

Give this edited version a try:

String source = "Hello < shaz = 2 Hello < shaz = 2 Hello";
String[] parts = Pattern.compile(" ").split(source);
int startIndex = 0;
for(String part: parts){        
    System.out.println(part + " : Pos " + (source.indexOf(part, startIndex) + 1));
    startIndex += part.length() + 1;
}

Prints:

Hello : Pos 1

< : Pos 7

shaz : Pos 9

= : Pos 14

2 : Pos 16

Hello : Pos 18

< : Pos 24

shaz : Pos 26

= : Pos 31

2 : Pos 33

Hello : Pos 35

Upvotes: 1

Oleg
Oleg

Reputation: 6324

You can use Matcher:

String string = "Hello, my name is";
Pattern pattern = Pattern.compile("\\w+"); // search for word, the regex might need adjustment
Matcher matcher = pattern.matcher(string);
// Will print the word and it's position
while (matcher.find()) {
    System.out.format("%d:%s%n", matcher.start() + 1, matcher.group());
}

Output:

1:Hello
8:my
11:name
16:is

Upvotes: 0

Related Questions