Search code examples
javaarraysstringoffset

Get the offset of a string


I have an Array of Strings that was split from a buffer string. Now each item in the array has a {value, offset, count, & hash}. How can I get the offset of the item in the array?

Example:

String buffer = aVeryLongString;
String[] splitStringArray = buffer.split(regex);

for(String s: splitStringArray) {   
    // Get the offset of each item
    // Do something
}

Solution

  • String buffer = aVeryLongString;
    String[] splitStringArray = buffer.split(regex);
    
    int offset = -1;
    for(String s: splitStringArray) {
        offset = buffer.indexOf(s, offset + 1); // avoid duplicates
        System.out.println(offset);
    }
    

    Using String.indexOf(String str, int offset) you can find out the offset of a string. It starts searching for the string at the given offset. So using the offset of the previous string will solve the problem with the duplicates.