Write own code for Java String indexOf() to find position of a given string in a source string

Let us first see what java String indexOf() does . It returns position of the given character / substring in a given String from the first occurance or starting from the specified position. IndexOf() is overloaded into four methods.
1. indexOf(int ch) - Returns the position / index of the given charater with in this string .
2. indexOf(int ch, int fromIndex) - Same as the above method but search starts from the the specified index.
3. indexOf(String str) - Returns the position / index of the given String with in this string
4. int indexOf(String str, int fromIndex) - Same as the 3rd method but search starts from the the specified index.
Now let us write code for indexOf(String source, String substr, int startPos, int occurrence, char caseSensitive) which does the same work with more options using Regexp, where source is the original string to search in , substr is the substring to be searched in the original string , startPos is the starting position to search , occurrence is used to tell which match to get. There may be more than one substring in the given string . If we give occurrence is 2 , then it will return the position of the second match. Matching can be done using CaseSensitive or Case In Sensitive . We have to pass 'N' for CaseInSensitive .
    
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
class customIndexOf
{
public static void main(String args[])
{
String source="Using Db2 UDB , Udfs can be created. DB2 UDFs is DB2 User Defined Functions";
String sub="db2";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,2,'N' ));
sub="UDFs";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,1,'Y' ));
sub="c";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,1,'N' ));
sub="DB2";
System.out.println("Using Java Index of () Position of " + sub + " = "+ (source.indexOf(sub, 0)+1));
}

public static int indexOf(String source, String substr, int startPos, int occurrence, char caseSensitive)
{
int position = 0;
int flag=2;
int occurrenceCount = 0;
if(caseSensitive=='Y') flag=0;
if ( source == null || source.length()==0) return -1;
Pattern pattern=null;
try
{
pattern = Pattern.compile(substr, flag);
}
catch (PatternSyntaxException e)
{
return 0;
}
Matcher matcher = pattern.matcher(source);
if (matcher.find(startPos))
{
position = matcher.start()+ 1;
occurrenceCount++;
while ((occurrenceCount < occurrence) && (matcher.find()))
{
position = matcher.start() + 1;
occurrenceCount++;
}
}

if (occurrenceCount!=occurrence) position =0 ;
return (position);
}
}



Output:

0 comments:

Post a Comment

 
Copyright 2011 Java Online