Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

tokenize name to 23 and PM separately

  Asked By: Boell    Date: May 18    Category: Java    Views: 530
  

i have a very specific question.

string name = "23PM"

now I need to tokenize name to 23 and PM separately.

for this we need to use string tokenizer. thats easy
when there is delimiter like ./space ... here is no
specific delimiter.

does any one have a suggestion/solution to this problem?

Share: 

 

5 Answers Found

 
Answer #1    Answered By: Katrina Edwards     Answered On: May 18

use Java Regex (only available on JDK 1.4)...
here is my code :

/*****************************************************************
import java.util.regex.*;

public class MyRegex {
public static void main(String[] args) {
myInput = "23AM";
myRegex = "^([0-9]{1,2})([AP]M)$" ;
// this regex mean : match only with a string  that have 1 or 2 num chars and
//followed by a/A or p/P and m/M ....

myPattern = Pattern.compile(myRegex);
myMatcher = myPattern.matcher(myInput);

if(myMatcher.find()){
System.out.println("Matched "+ myMatcher.groupCount());
for(int i=0; i <= myMatcher.groupCount(); i++) {
// print the matched, 0th index for indicates the global matching
System.out.println(i+" "+myMatcher.group(i));
}
} else
{
// input was invalid / not matched / not found
System.out.println("Unmatched");
}
}

private static String myRegex ; // string that contain regex pattern ;
private static Pattern myPattern ;
private static String myInput ;
private static Matcher myMatcher ;
}

 
Answer #2    Answered By: Eddie Austin     Answered On: May 18

That was a cool tip .. what are the other new features of jdk1.4 ?

 
Answer #3    Answered By: Antonio Dunn     Answered On: May 18

here's my type of code, is'nt it simple??

class Charactering
{
public static void main(String args[])
{
String name = "23AM";
char c;
String a="", b="";
for(int i=0; i< name.length(); i++)
{
c=name.charAt(i);
if ( Character.isDigit(c))
{
a += c;
continue;
}
else
{
b+=c;
}
}
System.out.println(a);
System.out.println(b);
}
}

 
Answer #4    Answered By: Holly Brown     Answered On: May 18

As best practice you might want to consider using a
StringCharacterIterator object to loop over the string  and a
StringBuffer instead of +=

 
Answer #5    Answered By: Maliha Malik     Answered On: May 18

I think using regex still the best (and the coolest) tricks...
your only need 5-10 line code to solve this

 
Didn't find what you were looking for? Find more on tokenize name to 23 and PM separately Or get search suggestion and latest updates.




Tagged: