String processing with C # .NET

I need help handling strings in C #.

I have a line with words and an empty space between them (I have some empty spaces between words, empty spaces are dynamic). I need to replace empty spaces with a dash "-"

I have something like this:

string stringForManipulation  = "word1    word2  word3"; 

      

I need to have this:

"word1-word2-word3"

      

Tpx

+3


source to share


5 answers


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

      



s

means a space, and +

means one or more events.

+12


source


You can use regular expressions:

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

      



This will replace all occurrences of one or more spaces with "-".

+6


source


For thoose without regex knowledge, this can be achieved with a simple split join operation:

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

      

+3


source


Just use

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

      

Replaces one or more spaces with one blue "-"

0


source


You can try the following

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

      

Created by Fiddle

0


source







All Articles