views:

64

answers:

4

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.

+2  A: 

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 <
Landei
+2  A: 

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
}
cristis
+3  A: 

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>
True Soft
Nice solution, although the OP was not asking for postions of this pattern but for position of the `<` and `>` chars (but maybe you solved what he was *really* looking at ;) )
Andreas_D
Thank you all. I use Pattern. =D True Soft, may i know more how to make regular expression?
See http://www.regular-expressions.info/. In this case, `<` means that you look after `<`; `[^>]` means a character that is not `>`; `*` is for zero or more characters, and `>` matches `>`. If your content is formed by one or more digits, you can use `<\d+>`. In java you must escape backslash: `"<\\d+>"`.
True Soft
A: 

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));
    }
}
wds