开发者

String , char double convert going along string

so say if i had a string like "3+3-1*2/3开发者_StackOverflow=" how would i go through the string looking at each character and if its a number turn it to a double then if not turn it to a char??


iterate over the string, and for each character use Character.isDigit(char c) to determine if it is a digit or not.
after you try this, if you need some more help - write what have you tried and I'll try to further help you.


You can traverse through the String using a loop. For example:

for(int i = 0; i < mystring.length(); i++) {
    char character = mystring.charAt(i);
    // do stuff with character
}

You can check if it is a decimal character by using Character.isDigit(char).

You can convert a string to an integer using parseInt().


Hint: Double.valueOf(String s) will throw an exception if the given String can not be parsed to a double.


String currentSubstring = "";
for (int index = 0; index < myString.length(); index++) {
    char next = myString.charAt(index);
    if ((next >= '0' && next <= '9') || next == '.') {
        currentSubstring += next;
    }
    else {
        if (! "".equals(currentSubstring)) {
            System.out.println("Found a number:  " + Double.parseDouble(currentSubstring));
            currentSubstring = "";
        }
        System.out.println("Found a character:  " + next);
    }
}
//in case the string ended with some numbers
if (! "".equals(currentSubstring)) {
    System.out.println("Found a number:  " + Double.parseDouble(currentSubstring));
}


This will iterate thru your string and splits it into chunks of digits and ., or single operators. Note that operators are handled one-by one.

String input = "3+3-1*2/3=";
Pattern p = Pattern.compile("([0-9.]+|[^0-9.])");
Matcher m = p.matcher(input);

while (m.find ()) {
    String chunk = m.group();
    char c = chunk.charAt(0);
    if (c >= '0' && c <= '9' || c == '.') then {
        // numbers
    } else {
        // operator
    }
}

If you want to respect precedence you should reorder your chunks to Polish form, then do the calculations.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜