3

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

1
  • 2
    This question says "give me the codez". Show that you have tried something first before demanding a solution. stackoverflow.com/help/how-to-ask is a good start. Commented May 29, 2015 at 8:57

5 Answers 5

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

s means whitespace and + means one or more occurence.

Sign up to request clarification or add additional context in comments.

Comments

6

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 "-".

Comments

3

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

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

3 Comments

It can ... but this is one of those rare cases where regexes are the better answer as the regex solution is simpler and easier to read.
I agree that Regex code is shorter, but there're many people who are completely new to programming and don't know about regular expressions.
@cyberj0g - ...in which case they should definitely learn that regex is a thing. I'm not convinced that your solution is easier to comprehend for someone new to programming. Also, stating that "it can be done without regex" is good and true, but please add the "why it should be done without regex" part.
0

Simply use

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

Will replace single or multiple spaces with single '-'

Comments

0

You can try the following

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

Created a Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.