Home > Net >  How to insert a space between a number and a string in Java?
How to insert a space between a number and a string in Java?

Time:02-21

I am using the java.util.scanner feature in Java (awesome!) but I have yet to figure out how to scan numbers that have units attached. For example, I know that you can insert spaces between numbers and non-numeric characters so that "47mg" becomes "47 mg". That would solve it for most situations. However, none of the solutions I have found so far seem to handle numbers that have exponents in them (scientific/engineering notation). For example, I would like it to convert "47E-3mg" to "47E-3 mg". Any ideas on how to do this? Thanks!

Update: Here is more background. In C the class has a feature that is similar to the scanner bit it knows where a number stops and does not give an error if a string is attached. It just stops where the number stops. Here is a simple example in C :

istringstream myStream;
string tempString;
double tempDouble;
string myString = " USE 1.23E-3mg ";
myStream.str(myString);
myStream >> tempString;
cout << "String:" << tempString << ":" << endl;
myStream >> tempDouble;
cout <<"Double:"<<tempDouble<<endl;
myStream >> tempString;
cout << "String:" << tempString << ":" << endl;
return 0;

It will output: String:USE: Double:0.00123 String:mg:

Update 2: Based on one of the answers I think the solution is close. Here is what we have now. It almost works. Just need to handle multiple entries... Anyone see what can be changed?

//String myString = "1.23E-3"; //Works
//String myString = "1.23E-3mg"; //Works
//String myString = "1.23E-3g"; //Works
String myString = "1.23mg 1.23mg";
System.out.println(myString.replaceAll("([a-z] )$", " 
$1"));

CodePudding user response:

Lets say you had the following:

String [] data = {"43E-2mg", "96.2mg", "55cc"};

This lets you replace one or more characters at then end of a string with a space and those same characters.

for (String s : data) {
    s = s.replaceAll("([a-z] )$", " $1");
    System.out.println(s);
}

prints

43E-2 mg
96.2 mg
55 cc

If you want to capture the individual parts for extra processing you can split on the zero width gap between the amount and the unit.

  • (?<![a-z]) - not preceded by a-z
  • (?=[a-z] $) - followed by one or more a-z followed by a new line.
for (String s : data) {
    String[] parts = s.split("(?<![a-z])(?=[a-z] $)");
    System.out.println(Arrays.toString(parts));
}

prints

[43E-2, mg]
[96.2, mg]
[55, cc]

CodePudding user response:

You can use a StringBuilder

StringBuilder sb = new StringBuilder("47E-3mg");
sb.insert(sb.indexOf("mg"), " "); //insert(index, string)
System.out.println(sb);

Output: 47E-3 mg

  • Related