luke luke - 1 year ago 67
Java Question

Removing special character without using Java Matcher and Pattern API

I am trying to write one java program. This program take a string from the user as an input and display the output by removing the special characters in it. And display the each strings in new line

Let's say I have this string

after reading this string my program should display the output by removing the special characters like







Now I know there are already API available like Matcher and Patterns API in java to do this. But I don't want to use the API since I am a beginner to java so I am just trying to crack the code bit by bit.

This is what I have tried so far. What I have done here is I am taking the string from the user and stored the special characters in an array and doing the comparison till it get the special character. And also storing the new character in StringBuilder class.

Here is my code

import java.util.*;
class StringTokens{
public void display(String string){
StringBuilder stringToken = new StringBuilder();
char[] str = {' ','!',',','?','.','_','@'};
for(int i=0;i<string.length();i++){
for(int j =0;j<str.length;j++){
else {
public static void main(String[] args){
System.out.println("Enter only one line string");
StringTokens st = new StringTokens();

When I run this code I am only getting the special characters, I am not getting the each strings in new line.

Answer Source

I strongly agreed to what @GhostCat said. In Java there is already plenty of things has been done for you. All you need is to implement it in your code.
You don't need to re-invent the wheel unless it's your assignment to implement with some different solution.
People has already answered to your question in different ways.
And there is also a corrected version of your code already submitted
One of my answer is to use StringTokenizer class. You can go through this link for a reference StringTokenizer .

Here is the executed code and the better solution

import java.util.StringTokenizer;
public class StringTokens {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Enter only one line string");
        } else {
    public static void display(String string) {
      StringTokenizer st = new StringTokenizer(string,("[_\\@!?.', ]"));

As you can see here with just simple three lines of code has solved your problem very easily rather than writing 20 30 lines of code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download