jobs
jobs

Reputation: 53

Clean a string from whitespace

I want to clean String from unnecessary data, something like:

x, y, z,  g,  h

More precisely, I want delete g and h, becuase before the g and h character, i have 2 "space".

What is the fastest way to accomplish this?

Upvotes: 1

Views: 203

Answers (3)

Ousmane D.
Ousmane D.

Reputation: 56393

Another variant would be:

String data = "x, y, z,  g,  h";
data = Pattern.compile(",")
              .splitAsStream(data)
              .filter(s -> s.length() - s.trim().length() <= 1)
              .collect(Collectors.joining(","));

if for some reason you still want the last comma included then you can do:

data = Pattern.compile(",")
              .splitAsStream(data)
              .filter(s -> s.length() - s.trim().length() <= 1)
              .collect(Collectors.joining(",", "", ","));

Upvotes: 1

Ashutosh Ranjan
Ashutosh Ranjan

Reputation: 1

String str ="x,y,z, g, h;
String newString = str.replaceAll("[^a-zA-Z]","");

o/p:

newString = x,y,x,g,h

Note: if you want to delete g & h character use java split method.

Upvotes: -2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

Use String#replaceAll:

String input = "x, y, z,  g,  h";
input = input.replaceAll("\\s{2,}\\w+,?", "");

Upvotes: 3

Related Questions