Marko Radosevic
Marko Radosevic

Reputation: 150

String manipulation with C# .NET

I need help with string manipulation in c#.

I have string with words and empty spaces between them(I have more than one empty spaces between words, empty spaces are dynamic). I need to replace empty spaces with dash "-"

I have something like this:

string stringForManipulation  = "word1    word2  word3"; 

I need to have this:

"word1-word2-word3"

Tnx

Upvotes: 3

Views: 217

Answers (5)

cyberj0g
cyberj0g

Reputation: 3787

For thoose without knowledge of regular expressions, it can be achieved by simple split-join operation:

string wordsWithDashes = stringForManipulation.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries).Join('-')

Upvotes: 3

R4nc1d
R4nc1d

Reputation: 3113

You can try the following

string stringForManipulation  = "word1    word2  word3"; 
string wordsWithDashes  = String.Join(" ", stringForManipulation.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)).Replace(" ", "-");

Created a Fiddle

Upvotes: 0

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

You can use regular expressions:

string stringForManipulation = "word1    word2  word3";
string result = Regex.Replace(stringForManipulation, @"\s+", "-");

This will replace all occurences of one or more whitespace to "-".

Upvotes: 6

user786
user786

Reputation: 4364

Simply use

string result=Regex.Replace(str , @"\s+", "-")

Will replace single or multiple spaces with single '-'

Upvotes: 0

user2160375
user2160375

Reputation:

var result = Regex.Replace(stringForManipulation , @"\s+", "-");

s means whitespace and + means one or more occurence.

Upvotes: 12

Related Questions