0

If I have expression in a string variable like this 20+567-321, so how can I extract last number 321 from it where operator can be +,-,*,/

If the string expression is just 321, I have to get 321, here there is no operator in the expression

Vikas Prasad
  • 3,163
  • 5
  • 28
  • 39
sjso
  • 277
  • 2
  • 11

4 Answers4

4

You can do this by splitting your string based on your operators as following:

String[] result = myString.split("[-+*/]");

[+|-|*|/] is Regex that specifies the points from where your string should be split. Here, result[result.length-1] is your required string.

EDIT As suggested by @ElliotFrisch we need to escape - in regex while specifying it. So following pattern should also work:

String[] result = myString.split("[+|\\-|*|/]");

Here is the list of characters they need to be escaped.

Link.

Kaushal28
  • 5,377
  • 5
  • 41
  • 72
4

This seems to be an assignment for learning programming and algo, and also I doubt splitting using Regex would be efficient in a case where only last substring is required.

  1. Start from end, and iterate until the length of the string times.
  2. Declare a empty string say Result
  3. While looping, if any of those operator is found, return Result, else prepend the traversed character to the string Result.
  4. Return Result
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
0
String[] output = s.split("[+-/*]");
String ans = output[output.length-1];

Assumption here that there will be no spaces and the string contains only numbers and arithmetic operators.

[+-/*] is a regular expression that matches only the characters we provide inside the square brackets. We are splitting based on those characters.

รยקคгรђשค
  • 1,919
  • 1
  • 10
  • 18
0

If you wanna do it with StringTokenizer:

 public static void main(String args[])

{
   String expression = "20+567-321";
   StringTokenizer tokenizer = new StringTokenizer(expression, "+-*/");
   int count = tokenizer.countTokens();
   if( count > 0){
       for(int i=0; i< count; i++){
           if(i == count - 1 ){
               System.out.println(tokenizer.nextToken());
           }else{
               tokenizer.nextToken();
           }
       }
   } 
}

Recall you can specify multiple delimiters in StringTokenizer.

Siddharth Sachdeva
  • 1,812
  • 1
  • 20
  • 29