Reputation: 150
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
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
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
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
Reputation: 4364
Simply use
string result=Regex.Replace(str , @"\s+", "-")
Will replace single or multiple spaces with single '-'
Upvotes: 0
Reputation:
var result = Regex.Replace(stringForManipulation , @"\s+", "-");
s
means whitespace and +
means one or more occurence.
Upvotes: 12