How to remove the space between specific characters in a string?

So I have a line like this:

string sampleString = "this - is a string   - with hyphens  -     in it";

It should be noted that there is a random number of spaces to the left and right of the hyphen. The goal is to replace the space in my string with a hyphen (hence the problem with hypens in the string). So the result that I have to do should look like this:

"this-this-line-with-hyphen-in-it."

I am currently using:

sampleString.Trim().ToLower().Replace(" ", "-")

but this leads to the following result:

"this --- this is a string ------ with a hyphen -------- something"

Look for the cleanest, most concise solution for this.

Thank!

+3
source share
8 answers

Since everyone will offer a regex solution, I offer you a regex-free solution:

string s = "this - is a string   - with hyphens  -     in it";
string[] groups = s.Split(
                       new[] { '-', ' ' },
                       StringSplitOptions.RemoveEmptyEntries
                  );
string t = String.Join("-", groups);        
+9

System.Text.RegularExpressions.Regex.

:

Regex.Replace(sampleString, @"\s+-?\s*", "-");
+6

( , ).

, . :

[- ]+

, , . :

tokens = split(string," ")
for each token in tokens,
  if token = "-", skip it
  otherwise print "-" and the token
+1

Regex.Replace(sampleString, @"\s+", " ").Replace (" ", "-");
0

:

private static readonly Regex rxInternaWhitespace = new Regex( @"\s+" ) ;
private static readonly Regex rxLeadingTrailingWhitespace = new Regex(@"(^\s+|\s+$)") ;
public static string Hyphenate( this string s )
{
  s = rxInternalWhitespace.Replace( s , "-" ) ;
  s = rxLeadingTrailingWhitespace.Replace( s , "" ) ;
  return s ;
}
0

AND existing hypens, , . , , .

0

Regex:

var sampleString = "this - is a string   - with hyphens  -     in it";
var trim = Regex.Replace(sampleString, @"\s*-\s*", "-" );
0

Modes are your friend here. You can create a pattern where all consecutive spaces / hyphens are the only match.

  var hyphenizerRegex = new Regex(@"(?:\-|\s)+");
  var result = hyphenizerRegex.Replace("a - b c -d-e", "-");
0
source

Source: https://habr.com/ru/post/1787541/


All Articles