tags:

views:

42

answers:

3

Dear All, I have 2 input string 1)stack,over,flow 2)stack/over,flow,com I would like to print only strings(without special char)from the above 2 input for 1st input i used below function but for 2nd input i dont know how to process it.Pls give me solution.

st = new StringTokenizer("stack,over,flow", ",");
       while (st.hasMoreTokens())
        {
            String token = st.nextToken();
           System.out.println("token = " + token);
        }

output:

stack
over
flow
A: 

You need to format your question better, it's hard to follow. But if I read it correctly,

st = new StringTokenizer("stack,over,flow", ",/");

Should work just fine.

Derek Clarkson
Thanks a lot it works well.
Mohan
A: 

Can you define what you mean by a special char? Do you mean "only alphanumeric characters"?

If you want to remove all possible special characters and leave only alphanumeric characters, then you can use the following:

s = s.replaceAll("[^a-zA-Z0-9]", "");

If you want to print them one by one:

s = s.replaceAll("[^a-zA-Z0-9]", "/");
String[] splitString = s.split("/");
for(String str:splitString)
{
   System.out.println(str);
}

EIDT: Since you asked: the above code uses the enhanced for loop (also called the for-each loop) introduced by java 5. Using the 'normal' for loop, this is:

s = s.replaceAll("[^a-zA-Z0-9]", "/");
String[] splitString = s.split("/");
for(int i=0; i<splitString.length(); i++)
{
   String str = splitString[i];
   System.out.println(str);
}

Also:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

(from the javadoc)

Nivas
Can you pls tell me what is the str value in for loop.
Mohan
str is the loop variable. The code i mentioned uses the enhanced for loop of java 5. I have edited the answer to add the 'normal' for loop
Nivas
Cannot invoke length() on the array type String[] i got this error while compiling your edited code.
Mohan
String s="stack/over,flow,com"; i add this line only with your edited code.
Mohan
That is not very difficult, you could have tried yourself: instead of `splitString.length();` use `splitString.length;`
Nivas
Thanks a lot Nivas. It works fine.
Mohan
A: 

This should work for you in both the cases:

   String[] strArr=yourString.split("[/,]");
   for(String str:strArr)
   {
     System.out.println(str);
   }
Emil