Token - Smaller piece of a string
StringTokenizer used to tokenize the string based on the delimiter. Mostly, It used when reading from the comma separated file.
List of characters that count as delimiters, but in that list, each character is a single delimiter.
Sample Program
package com.javalearning.crazy;
import java.util.StringTokenizer;
public class StringTokenizerTest {
public static void main(String[] args) {
String in="Live = for Passion; Do = with Happiness;
Move = ahead with Purpose;";
StringTokenizer t=new StringTokenizer(in,"=;");
while(t.hasMoreTokens())
{
String key=t.nextToken();
String val=t.nextToken();
System.out.println(key+""+val);
}
}
}
String split
It split the string into token based on the regular expression [delimiter is a regular expression]
Comma separated delimiter you can use split(" *, *")
String[] split( String regularExpression )
regularExpression - Splits the string according to given regular expression.
String[] split( String reularExpression, int limit )
regularExpression - Splits the string according to given regular expression.
limit - The number of resultant substrings
Sample Program
package com.javalearning.crazy;
public class StringSplitSample {
public static void main(String[] args) {
String str = "Life-Teaches-Lesson-Every-Day";
String[] temp;
String delimiter = "-";
temp = str.split(delimiter);
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
}
}
Issues
Sometimes after calling split() the first array index holds a space character even though the string contains no leading space.
Pattern Matching
Pattern - Compiled representation of a regular expression.
Matcher - Resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression.
Sample Program
package com.javalearning.crazy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringPattern {
public static void main(String[] args) {
String splitregex = "because";
String searchString= "Famous Reply: No sentence can end with because because, because is a conjunction";
Pattern pattern = Pattern.compile(splitregex);
Matcher matcher = pattern.matcher(searchString);
if (matcher.find()) {
System.out.println(matcher.group(0));
} else {
System.out.println("Match not found");
}
}
}
This pattern matching mostly used in spam filtering projects and Dynamic application used projects [Project which uses more application forms and dynamic place holders]
No comments:
Post a Comment