简体   繁体   中英

Printing only string

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

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.

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 )

This should work for you in both the cases:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM