Replace Single WhiteSpace without replacing multiple WhiteSpace

I have a line in the format: abc def ghi xyz

I would like to finish it in the format: abcdefghi xyz

What is the best way to do this? In this particular case, I could simply remove the last three characters, remove the spaces and then add them at the end, but this will not work for cases where several spaces are in the middle of the line.

In short, I want to remove all individual spaces, and then replace all multiple spaces with one. Each of these steps in itself is quite simple, but combining them seems a little less simple.

I want to use regular expressions, but I would prefer not to.

+4
source share
5 answers

, , .

var pattern = @"  +"; // match two or more spaces
var groups = Regex.Split(input, pattern);

() :

var tokens = groups.Select(group => group.Replace(" ", String.Empty));

,

var result = String.Join(' ', tokens.ToArray());

, "" ( , ..) - \s '', , .

+4

, , , , , lookahead , :

// Replace all single whitespaces
for (int i = 0; i < sourceString.Length; i++)
{
    if (sourceString[i] = ' ')
    {
        if (i < sourceString.Length - 1 && sourceString[i+1] != ' ')
          sourceString = sourceString.Delete(i);
    }
}

// Replace multiple whitespaces
while (sourceString.Contains("  ")) // Two spaces here!
  sourceString = sourceString.Replace("  ", " ");

, ...

+2

REGEX :

string str = "abc def ghi         xyz";
var result = str.Split(); //This will remove single spaces from the result
StringBuilder sb = new StringBuilder();
bool ifMultipleSpacesFound = false;
for (int i = 0; i < result.Length;i++)
{
    if (!String.IsNullOrWhiteSpace(result[i]))
    {
        sb.Append(result[i]);
        ifMultipleSpacesFound = false;
    }
    else
    {
        if (!ifMultipleSpacesFound)
        {
            ifMultipleSpacesFound = true;
            sb.Append(" ");
        }
    }
}

string output = sb.ToString();

:

output = "abcdefghi xyz"
+2

, :

public static string RemoveUnwantedSpaces(string text)
{
    var sb = new StringBuilder();
    char lhs = '\0';
    char mid = '\0';

    foreach (char rhs in text)
    {
        if (rhs != ' ' || (mid == ' ' && lhs != ' '))
            sb.Append(rhs);

        lhs = mid;
        mid = rhs;
    }

    return sb.ToString().Trim();
}

:

( ). lhs, mid rhs.

rhs :

  • , .
  • , , , , , .
  • , , ( ) , : , , . , .

, , lhs mid . , , , \0, , .

+1

regex solution:

Regex.Replace("abc def ghi    xyz", "( )( )*([^ ])", "$2$3")

"abcdefghi xyz"

:

:

var tmp = Regex.Replace("abc def ghi    xyz", "( )([^ ])", "$2")

tmp - "abcdefghi xyz" :

var result = Regex.Replace(tmp, "( )+", " ");

result "abcdefghi xyz"


:

( x 3 tmp).

.

:

, . ( ( ) ). , "abc def ghi xyz" :

match: " d" group1: " " group2: "d"

match: " g" group1: " " group2: "g"

match: " x" group1: " " group2: "x"

Regex.Replace ( )

+1

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


All Articles