Sandeep Thomas
Sandeep Thomas

Reputation: 4759

Remove all spaces from a string, that is only present before and after a delimitter

Ive a scenario to remove spaces from a string. But not all spaces. if so I can accomplish it simply using replace or trim. But the problem is to remove all spaces that is present before and after a specific delimitter in that string

For example consider the string

Alex T Paul# John Tenor # Jeremy Cook # Emerson #Peter

Here there is lots of spaces in the string. But we need to replace all the spaces that is exists before and after the delimiter #

So the final text should be like

Alex T Paul#John Tenor#Jeremy Cook#Emerson#Peter

Upvotes: 1

Views: 70

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

You can try using regular expressions:

  String source = "Alex T Paul# John Tenor # Jeremy Cook # Emerson #Peter";

  // Alex T Paul#John Tenor#Jeremy Cook#Emerson#Peter
  String result = Regex.Replace(source, @" *# *", "#");

Upvotes: 3

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

var delimiter = '#';
var input = "Alex T Paul# John Tenor # Jeremy Cook # Emerson #Peter";

var parts = input.Split(delimiter);
var result = string.Join(delimiter.ToString(), parts.Select(s => s.Trim()));

Upvotes: 3

Related Questions