Hi,
I want to search Wildcard('<', '>') in a string, count them and get their positions in java. My string is like below
Peter <5554>, John <5556>,
which function should I use? Thank you.
Hi,
I want to search Wildcard('<', '>') in a string, count them and get their positions in java. My string is like below
Peter <5554>, John <5556>,
which function should I use? Thank you.
One solution would be to use String.indexOf(). You can do something like this:
String s = "Peter <5554>, John <5556>";
List<Integer> posGt = new ArrayList<Integer>();
int i = 0;
while((i = s.indexOf('>', i)) != -1) {
posGt.add(i++);
}
...
//the same for <
You can implement it with repeated indexOf
and substring
:
String s = "Peter <5554>, John <5556>,"
int count = 0;
ArrayList<Integer> positions = new ArrayList<Integer>();
int cut = 0;
while(true) {
// search for <
int index = s.indexOf('<');
if (index < 0)
break;
// search for >
int index2 = s.indexOf('>');
if (index2 < 0)
break; // or throw exception
// update count and positions
count++;
positions.add(index+cut);
s = s.substring(index2+1);
cut += index2+1; // used to compute the initial position since we're cutting the string
}
You should use Pattern and Matcher:
Pattern pattern = Pattern.compile("<[^>]*>");
Matcher matcher = pattern.matcher("Peter <5554>, John <5556>,");
while (matcher.find()) {
System.out.println("index="+matcher.start()+" - "+matcher.group());
}
Output:
index=6 - <5554>
index=19 - <5556>
Repeated indexOf
with fromIndex
looks like a nice solution. The alternative would have been iterating over the string and using charAt
(arguably the obvious solution, if only java had sane string indexing):
String s = "Peter <5554>, John <5556>,";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '<' || s.charAt(i) == '>') {
System.out.printf("index %d - %s\n", i, s.charAt(i));
}
}