C #에서 여러 공백을 단일 공백으로 바꾸는 방법은 무엇입니까? 4

C #에서 문자열의 여러 공백을 하나의 공백으로 바꾸려면 어떻게해야합니까?

예:

1 2 3  4    5

될 것입니다 :

1 2 3 4 5


답변

string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");

답변

나는 사용하고 싶다 :

myString = Regex.Replace(myString, @"\s+", " ");

모든 종류의 공백 (예 : 탭, 줄 바꿈 등)을 포착하여 단일 공백으로 바꿉니다.


답변

string xyz = "1   2   3   4   5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));

답변

나는 Matt의 대답이 최고라고 생각하지만 그것이 옳다고 믿지 않습니다. 줄 바꾸기를 바꾸려면 다음을 사용해야합니다.

myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);

답변

LINQ를 사용하는 또 다른 접근법 :

 var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
 str = string.Join(" ", list);

답변

그것은 모든 것보다 훨씬 간단합니다.

while(str.Contains("  ")) str = str.Replace("  ", " ");

답변

간단한 작업으로도 정규식이 느려질 수 있습니다. 이것은 모든에서 사용할 수있는 확장 메소드를 작성합니다 string.

    public static class StringExtension
    {
        public static String ReduceWhitespace(this String value)
        {
            var newString = new StringBuilder();
            bool previousIsWhitespace = false;
            for (int i = 0; i < value.Length; i++)
            {
                if (Char.IsWhiteSpace(value[i]))
                {
                    if (previousIsWhitespace)
                    {
                        continue;
                    }

                    previousIsWhitespace = true;
                }
                else
                {
                    previousIsWhitespace = false;
                }

                newString.Append(value[i]);
            }

            return newString.ToString();
        }
    }

다음과 같이 사용됩니다.

string testValue = "This contains     too          much  whitespace."
testValue = testValue.ReduceWhitespace();
// testValue = "This contains too much whitespace."