The Learner
The Learner

Reputation: 3917

java comparing the first 2 characters

I want to find in a Text the starting is number followed by .

example:
1.
11.
111.

My code for x. ( x is number) this is working . issue is when x is more than 2 digits.

x= Character.isDigit(line.charAt(0));
if(x)
if (line.charAt(1)=='.')

How can I extend this logic to see if x is a integer followed by .

My first issue is : I need to fond the given line has x. format or not where x is a integr

Upvotes: 3

Views: 216

Answers (5)

Amarnath
Amarnath

Reputation: 8865

public class ParsingData {
public static void main(String[] args) {
    //String one = "1.";
    String one = "11.";

    int index = one.indexOf(".");

    String num = (String) one.subSequence(0, index);

    if(isInteger(num)) {
            int number = Integer.parseInt(num);
            System.out.println(number);
    }
    else 
        System.out.println("Not an int");
}

public static boolean isInteger(String string) {
    try {
        Integer.valueOf(string);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
}

Upvotes: 1

Trasvi
Trasvi

Reputation: 1247

Edit: Whoops, misread.

try this:

    public static boolean prefix(String s) {
        return s.matches("[0-9]+\\.");
    }

Upvotes: 1

aviad
aviad

Reputation: 8278

You can use regex:

Pattern.compile("C=(\\d+\\.\\d+)")

However, more general would be:

Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")

Now to work with the Pattern you do something like:

Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?");
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
// Check all occurances
while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end() + " ");
    System.out.println(matcher.group());
}

Upvotes: 1

turtledove
turtledove

Reputation: 25904

Why not using a regular expression?

([0-9]+)[.]

Upvotes: 1

codaddict
codaddict

Reputation: 455020

You can use the regex [0-9]\. to see if there exists a digit followed by a period in the string.

If you need to ensure that the pattern is always at the beginning of the string you can use ^[0-9]+\.

Upvotes: 4

Related Questions