-2

if I read 1symbol2 as a String i can split that using String.split("") into 3 variables but if I read 12 symbol 16 as a string and if I apply String.split(" ") it is split into 6 variables. How can I split that into 3 variables that are (12, symbol,16)? Note: The following any of them can be considered as Symbols +,-,*,/,%,~,!,@,#,$,^,&

teja
  • 19
  • 6

3 Answers3

1

If you can separate the three string 12 + and 16 with a comma, means something like --> 12,+,16 then below code will work for you.

String str = "12,+,16";
String a[] = str.split(",");
System.out.println(a[0]+" "+a[1]+" "+a[2]);

Result will be --> 12 + 16

Try this and let me know

coding_with_sabs
  • 121
  • 1
  • 2
  • 10
1

You can use following regex to separate your string in parts:

String myString = "12+16";
String[] result = myString.split("(?<=[-+*/])|(?=[-+*/])");
System.out.println(Arrays.toString(result));

Output:

[12,+,16]

Mustahsan
  • 3,852
  • 1
  • 18
  • 34
0

Instead of String.split(" "), you can just do: String.split("+")

BlackBeard
  • 10,246
  • 7
  • 52
  • 62