开发者

How to check that the string contains the number format in Java?

开发者 https://www.devze.com 2023-04-13 05:51 出处:网络
I am new to applet concept. I want to implement the one application. The applet have 2 text areas and one button. The first text area is the input(means it contains some text).Second Text area is empt

I am new to applet concept. I want to implement the one application. The applet have 2 text areas and one button. The first text area is the input(means it contains some text).Second Text area is empty.If you click on the button then the text in the first text area is parsed(here parsed means first text area text contains some text right? that text contains some number here that numbers will be removed and remaining text will be pasted in the second text area) EX: Text area1: 1. stack Overflow 2 Google 3 yahoo after button click Text area2: stack Overflow Google Yahoo

Here how to check the number in the string? and how to get the string up to the number.

public cla开发者_JAVA百科ss parsetextdata extends Applet implements ActionListener{

    TextArea ta1,ta2;
    Button parse;
    public void init() { 
        ta1 = new TextArea();

        ta1.setText("1. Naresh Repalle 2. Lakshman Yalavarthy 3. Rajendra Batchu 4. Bhart Chand Yalavrthy ");
        add(ta1); 

        parse = new Button();
        parse.setLabel("parse");
        add(parse); 

        ta2 = new TextArea();    
        add(ta2);              

        parse.addActionListener(this);

      }

    @Override
    public void actionPerformed(ActionEvent button) {

        if(button.getSource() == parse)
        {
            String text = ta1.getText();        
            ta2.setText(text);
        }
    }

}


If your goal is simply to remove numbers (and whitespace as your examples do) you can simply use String.replaceAll like this:

ta2.setText(text.replaceAll("[0-9]+ ?", ""));


Just use:

text.replaceAll("[\\w]*[0-9.]+[\\w]*", "\n");

It replaces all numeric characters and dots with a newline character, so if you put the result to a JTextArea, every name will be on a single line.

To get the Strings between the numbers, use the split() method.

String[] names = text.split("[\\w]*[0-9.]+[\\w]*");

The regex now also removes whitespaces between the numbers and the names. String[] names will contain the single names.


You can use following code

private static ArrayList <Character> getNumberRemoved(String string) {

    ArrayList <Character> list = new ArrayList <Character> ();
    char [] inString = string.toCharArray();
    for (char ch : inString)
    {
        if (ch >= '0' && ch <='9')
            continue;
        list.add(ch);
    }

    return list;
}

This will take O(n) time. basically walk through the characters and skip numbers.

0

精彩评论

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

关注公众号