Showing posts with label regex. Show all posts
Showing posts with label regex. Show all posts

Java program that replaces two or more consecutive characters / blanks in a string by a single character / blank. Use Regular Expression.

Sometimes interview questions may be little bit tricky . The following tricky questions may be asked
1. A string has thousand or two thousand zeros . Replace all consecutive zeros with a single zero without using loop
2 String str = "200000000000000000000000500000000000000000" . Make it to 2050 without using loop
The answer should be in one line and should be a general solution to all similar problems , should not be a specific solution to a particular problem.
In college / school computer practical lab , the following program may be given to solve. WAP that replaces two or more consecutive characters / blanks in a string by a single character / blank. For example, if the input is Keppplarrr-222 2b issss 222.444 timmes the sizzzze of the eeearth and the output should be Keplar-2 2b is 2.4 times the size of the earth.
The solution to all the above questions, without using loop will be using Regular Expression (RegExp) . The answer using RegExp is , str.replaceAll( "(.)\\1+", "$1" )
"(.)\\1+ " - The meaning of the metacharater used in the expression is
(.) - match any charater
\1 - matchs text similar to that matched within the first parenthesized .
+ - One or more times
The program for the above questions is as follows . The problems are solved in two ways . One is using Regular Expressions and another is using for loop. In method 2 , charAt (int index), deleteCharAt(int index) are used where char charAt (int index) - Returns the char value at the specified index and StringBuffer deleteCharAt(int index) - Removes the char at the specified index*/
    
class ReplaceConsecutiveChar
{
public static void main (String args[])
{
//String inputStr ="Keppplarrr-222 2b issss 222.444 timmes the sizzzze of the eeearth";
String inputStr ="200000000000000000000000500000000000000000";
String newString=ReplConsectiveCharM1(inputStr);
String newString1 = ReplConsectiveCharM2(inputStr);
System.out.println("Input String : " + inputStr);
System.out.println("Using RegExp : "+ newString + "\nUsing For Loop : " + newString1);
}

// Method 1 : Using RegExp
public static String ReplConsectiveCharM1(String str)
{
return(str.replaceAll( "(.)\\1+", "$1" ));
}

// Method 2 : Using For Loop
public static String ReplConsectiveCharM2(String s)
{
StringBuffer sb=new StringBuffer(s);
for (int i=0; i<sb.length() ; i++)
{
for (int j=i+1; j<sb.length() ; j++)
{
if (sb.charAt(i) ==sb.charAt(j) )
{
sb.deleteCharAt(j);
j--;
}
else break;
}
}
return sb.toString();
}

}


Output


Read more...

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:

Read more...

 
Copyright 2011 Java Online