Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

java - Insert space after every one or two characters in string

I need to write code to correct user input. The input is a mathematical expression in infix form. In order for my calculations to be correct, i need each operand spaced away from the operator.

Can you please help me write a method that will provide the following expected results.

Expected input: 13*21-5+33 Expected Output: 13 * 21 - 5 + 33

Research I have done: I could only find out how to add spaces between every character in the string and that will not work for calculating expressions with double digit values. Ie: 1 3 * 2 1 - 5 + 3 3. How to insert Space after every Character of an existing String in Java?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Look for digits using regex then surround them with spaces:

string.replaceAll("\d+", " $0 ").trim(); // trim in case numbers are first/last

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...