0

I am using the below code to find the nth occurrence of , (comma) in the string. And once I get this, I need to get the value between this occurrence(nth) and next occurrence (n+1th occurrence)

Please let me know if I am going wrong somewhere.

 int ine=nthOccurence(line,18);  
         String strErrorCode=line.substring(ine,line.indexOf(",", ine+1));
String errorCode=strErrorCode.substring(1, strErrorCode.length());

The function

public static int nthOccurence(String strLine,int index)
  {

      char c=',';
            int pos = strLine.indexOf(c, index);
            while (index-- > 0 && pos != -1)
            {
                pos = strLine.indexOf(c, pos+1);
               // System.out.println("position is " +  pos);
            }
                return pos;
        }

Thanks.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
AngelsandDemons
  • 2,823
  • 13
  • 47
  • 70
  • I'm confused. What `String errorCode=strErrorCode.substring(1, strErrorCode.length());` is supposed to accomplish? – PM 77-1 Oct 09 '13 at 14:59
  • The string returned contains a - at the beginning. I need to remove it..Hence. – AngelsandDemons Oct 09 '13 at 15:03
  • 1
    [`substring` with two `int` parameters](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int, int)) uses the 1st (from) as inclusive and 2nd (to) as exclusive. Does it agree with your definition of "*between*"? – PM 77-1 Oct 09 '13 at 15:03
  • But is the code correct..I mean I am getting variable output..I am not able to bet on the index. – AngelsandDemons Oct 09 '13 at 15:03

2 Answers2

2

Here's an alternative approach, also more readable:

public static String getAt(String st, int pos) {
    String[] tokens = st.split(",");
    return tokens[pos-1];
}

public static void main(String[] args) {
    String st = "one,two,three,four";
    System.out.println(getAt(st, 1)); // prints "one"
    System.out.println(getAt(st, 2)); // prints "two"
    System.out.println(getAt(st, 3)); // prints "three"
}
Udo Klimaschewski
  • 5,150
  • 1
  • 28
  • 41
2

Something like this?

public static int nthOccurence(String strLine,int index){
  String[] items = strLine.split(",");
  if (items.length>=index)
      return items[index];
  else
      return "";//whatever you want to do it there's not enough commas
}
tom
  • 2,704
  • 16
  • 28
  • I'm not sure what you mean. Do you mean you need the position in the string? The start position, end position or both. Do you include the commas in that or not. You need to be more clear. – tom Oct 09 '13 at 15:14