简体   繁体   中英

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 Abc@xyz,2016!horrible_just?kidding after reading this string my program should display the output by removing the special characters like

Abc
xyz
2016
horrible
just
kidding

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();
        stringToken.setLength(0);
        char[] str = {' ','!',',','?','.','_','@'};
        for(int i=0;i<string.length();i++){
            for(int j =0;j<str.length;j++){
                if((int)string.charAt(i)!=(int)str[j]){
                    stringToken.append(str[j]);
                }
                else    {
                    System.out.println(stringToken.toString());
                    stringToken.setLength(0);
                        }
            }
        }
    }
public static void main(String[] args){
    if(args.length!=1)
        System.out.println("Enter only one line string");
    else{
        StringTokens st = new StringTokens();
        st.display(args[0]);
        }       
    }
}

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

One easy way - use a set to hold all invalid characters:

Set<Character> invalidChars = new HashSet<>(Arrays.asList('$', ...));

Then your check boils down to:

if(invaidChars.contains(string.charAt(i)) {
  ... invalid char  
} else {
  valid char
}

But of course, that still means: you are re-inventing the wheel. And one does only re-invent the wheel, if one has very good reasons to. One valid reason would be: your assignment is to implement your own solution.

But otherwise: just read about replaceAll . That method does exactly what your current code; and my solution would be doing. But in a straight forward way; that every good java programmer will be able to understand!

So, to match your question: yes, you can implement this yourself. But the next step is to figure the "canonical" solution to the problem. When you learn Java, then you also have to focus on learning how to do things "like everybody else", with least amount of code to solve the problem. That is one of the core beauties of Java: for 99% of all problems, there is already a straight-forward, high-performance, everybody-will-understand solution out there; most often directly in the Java standard libraries themselves! And knowing Java means to know and understand those solutions.

Every C coder can put down 150 lines of low-level array iterating code in Java, too. The true virtue is to know the ways of doing the same thing with 5 or 10 lines!

I can't comment because I don't have the reputation required. Currently you are appending str[j] which represents special character. Instead you should be appending string.charAt(i). Hope that helps.

stringToken.append(str[j]);

should be

stringToken.append(string.charAt(i));

Here is corrected version of your code, but there are better solutions for this problem.

public class StringTokens {

    static String specialChars = new String(new char[]{' ', '!', ',', '?', '.', '_', '@'});

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Enter only one line string");
        } else {
            display(args[0]);
        }
    }

    public static void display(String string) {
        StringBuilder stringToken = new StringBuilder();
        stringToken.setLength(0);
        for(char c : string.toCharArray()) {
            if(!specialChars.contains(String.valueOf(c))) {
                stringToken.append(c);
            } else {
                stringToken.append('\n');
            }
        }
        System.out.println(stringToken);
    }
}
public static void main(String[] args) {
    String a=",!?@_."; //Add other special characters too
    String test="Abc@xyz,2016!horrible_just?kidding"; //Make this as user input
    for(char c : test.toCharArray()){
        if(a.contains(c+""))
        {
            System.out.println(); //to avoid printing the special character and to print newline
        }
        else{
            System.out.print(c);
        }
    }
}

you can run a simple loop and check ascii value of each character. If its something other than AZ and az print newline skip the character and move on. Time complexity will be O(n) + no extra classes used.

        String str = "Abc@xyz,2016!horrible_just?kidding";

        char charArray[] = str.toCharArray();

        boolean flag=true;;
        for (int i = 0; i < charArray.length; i++) {
            int temp2 = (int) charArray[i];

            if (temp2 >= (int) 'A' && temp2 <= (int) 'Z') {
                System.out.print(charArray[i]);
                flag=true;
            } else if (temp2 >= (int) 'a' && temp2 <= (int) 'z') {
                System.out.print(charArray[i]);
                flag=true;
            } else {
                if(flag){
                    System.out.println("");
                    flag=false;
                }
            }
        }

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