开发者

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 kn开发者_如何学Goow 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


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)


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.


This should work for you in both the cases:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜