C#에서 여러 공간을 단일 공간으로 대체하려면 어떻게 해야 합니까?
문자열의 여러 공백을 C#에서 하나의 공백으로 대체하려면 어떻게 해야 합니까?
예:
1 2 3 4 5
다음과 같습니다.
1 2 3 4 5
즐겨 사용하는 항목:
myString = Regex.Replace(myString, @"\s+", " ");
모든 종류의 공백(예: 탭, 새 줄 등)을 캡처하고 단일 공백으로 대체하기 때문입니다.
string sentence = "This is a sentence with multiple spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
string xyz = "1 2 3 4 5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
저는 매트의 대답이 가장 좋다고 생각하지만, 저는 그것이 완전히 옳다고 생각하지 않습니다.새 줄을 바꾸려면 다음을 사용해야 합니다.
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."
myString = Regex.Replace(myString, " {2,}", " ");
마음에 들지 않는 사람들을 위해Regex여기 다음을 사용하는 방법이 있습니다.StringBuilder:
public static string FilterWhiteSpaces(string input)
{
if (input == null)
return string.Empty;
StringBuilder stringBuilder = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
제 테스트에서 이 방법은 정적으로 컴파일된 Regex에 비해 매우 큰 중소형 문자열 집합으로 평균 16배 더 빨랐습니다.컴파일되지 않았거나 정적이지 않은 정규식과 비교하면 훨씬 더 빠를 것입니다.
선행 또는 후행 공백은 제거되지 않으며 이러한 경우가 여러 번 발생할 뿐입니다.
이 버전은 더 짧은 버전으로, 한 번만 이 작업을 수행하는 경우에만 사용해야 합니다. 새 인스턴스가 생성되기 때문입니다.Regex클래스가 호출될 때마다 표시합니다.
temp = new Regex(" {2,}").Replace(temp, " ");
정규 표현식에 익숙하지 않은 경우 다음과 같은 간단한 설명이 있습니다.
그{2,}에서는 앞에 나오는 문자를 정규식으로 검색하고 2회에서 무제한 사이의 하위 문자열을 찾습니다.
그.Replace(temp, " ")문자열 임시의 모든 일치 항목을 공백으로 바꿉니다.
이 옵션을 여러 번 사용하려면 컴파일 시 정규식 IL을 생성하므로 더 나은 옵션이 있습니다.
Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");
이를 한 줄의 솔루션으로 간편하게 수행할 수 있습니다!
string s = "welcome to london";
s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");
원하는 경우 다른 대괄호(또는 다른 문자)를 선택할 수 있습니다.
정규군도, 링크도...선행 및 후행 공백을 제거하고 내장된 다중 공간 세그먼트를 하나의 공간으로 줄입니다.
string myString = " 0 1 2 3 4 5 ";
myString = string.Join(" ", myString.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries));
결과: "0 1 2 3 4 5"
// Mysample string
string str ="hi you are a demo";
//Split the words based on white sapce
var demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
//Join the values back and add a single space in between
str = string.Join(" ", demo);
// output: string str ="hi you are a demo";
Joel에 따르면, 다른 답변들을 통합하고, 제가 진행함에 따라 약간 개선되기를 바랍니다.
이 작업은 다음을 통해 수행할 수 있습니다.
string s = Regex.Replace (
" 1 2 4 5",
@"[ ]{2,}",
" "
);
또는 다음과 함께:
static class StringExtensions
{
public static string Join(this IList<string> value, string separator)
{
return string.Join(separator, value.ToArray());
}
}
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");
나는 방금 새로운 글을 썼습니다.Join제가 좋아하는 것을, 그래서 저는 그것으로 다시 대답하려고 생각했습니다:
public static string Join<T>(this IEnumerable<T> source, string separator)
{
return string.Join(separator, source.Select(e => e.ToString()).ToArray());
}
이것의 멋진 점 중 하나는 요소에서 ToString()을 호출하여 문자열이 아닌 컬렉션으로 작동한다는 것입니다.사용량은 여전히 동일합니다.
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");
많은 답변이 올바른 출력을 제공하고 있지만 최고의 성능을 원하는 사람들을 위해 놀라나의 답변(성능에 대한 최고의 답변)을 약 10% 향상시켰습니다.
public static string MergeSpaces(this string str)
{
if (str == null)
{
return null;
}
else
{
StringBuilder stringBuilder = new StringBuilder(str.Length);
int i = 0;
foreach (char c in str)
{
if (c != ' ' || i == 0 || str[i - 1] != ' ')
stringBuilder.Append(c);
i++;
}
return stringBuilder.ToString();
}
}
정규식 패턴 사용
[ ]+ #only space
var text = Regex.Replace(inputString, @"[ ]+", " ");
이것이 꽤 오래된 것이라는 것을 알지만, 거의 같은 것을 성취하려고 노력하는 동안 우연히 이것을 발견했습니다.RegEx Buddy에서 이 솔루션을 찾았습니다.이 패턴은 모든 이중 공간을 단일 공간으로 대체하고 선행 및 후행 공간도 자릅니다.
pattern: (?m:^ +| +$|( ){2,})
replacement: $1
빈 공간을 다루고 있기 때문에 읽기가 조금 어렵기 때문에 여기에 "_"로 대체된 "공간"이 있습니다.
pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.
"(?m:" 구성은 "다중 줄" 옵션을 활성화합니다.저는 일반적으로 패턴 자체 내에 가능한 모든 옵션을 포함하여 보다 자기 통제적인 것을 선호합니다.
이것으로 공백을 제거할 수 있습니다.
while word.contains(" ") //double space
word = word.Replace(" "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.
정규식을 사용하지 않는 경우:
while (myString.IndexOf(" ", StringComparison.CurrentCulture) != -1)
{
myString = myString.Replace(" ", " ");
}
짧은 문자열에는 사용 가능하지만 공백이 많은 긴 문자열에서는 성능이 저하됩니다.
이 방법을 사용해 보세요.
private string removeNestedWhitespaces(char[] st)
{
StringBuilder sb = new StringBuilder();
int indx = 0, length = st.Length;
while (indx < length)
{
sb.Append(st[indx]);
indx++;
while (indx < length && st[indx] == ' ')
indx++;
if(sb.Length > 1 && sb[0] != ' ')
sb.Append(' ');
}
return sb.ToString();
}
다음과 같이 사용합니다.
string test = removeNestedWhitespaces("1 2 3 4 5".toCharArray());
놀로나 원본 답변에 대한 약간의 수정 사항이 있습니다.
문자가 단순한 공백이 아니라 공백인지 확인하려면 다음을 사용합니다.
여러 개의 공백 문자를 단일 공백으로 바꿉니다.
public static string FilterWhiteSpaces(string input)
{
if (input == null)
return string.Empty;
var stringBuilder = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
if (i == 0 || !char.IsWhiteSpace(c) || (char.IsWhiteSpace(c) &&
!char.IsWhiteSpace(strValue[i - 1])))
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
불량배가 되는 건 어때요?
public static string MinimizeWhiteSpace(
this string _this)
{
if (_this != null)
{
var returned = new StringBuilder();
var inWhiteSpace = false;
var length = _this.Length;
for (int i = 0; i < length; i++)
{
var character = _this[i];
if (char.IsWhiteSpace(character))
{
if (!inWhiteSpace)
{
inWhiteSpace = true;
returned.Append(' ');
}
}
else
{
inWhiteSpace = false;
returned.Append(character);
}
}
return returned.ToString();
}
else
{
return null;
}
}
StringBuilder와 Enumerable이 혼합되어 있습니다.문자열에 대한 확장 메서드로 Aggregate():
using System;
using System.Linq;
using System.Text;
public static class StringExtension
{
public static string CondenseSpaces(this string s)
{
return s.Aggregate(new StringBuilder(), (acc, c) =>
{
if (c != ' ' || acc.Length == 0 || acc[acc.Length - 1] != ' ')
acc.Append(c);
return acc;
}).ToString();
}
public static void Main()
{
const string input = " (five leading spaces) (five internal spaces) (five trailing spaces) ";
Console.WriteLine(" Input: \"{0}\"", input);
Console.WriteLine("Output: \"{0}\"", StringExtension.CondenseSpaces(input));
}
}
이 프로그램을 실행하면 다음과 같은 출력이 생성됩니다.
Input: " (five leading spaces) (five internal spaces) (five trailing spaces) "
Output: " (five leading spaces) (five internal spaces) (five trailing spaces) "
오래된 학교:
string oldText = " 1 2 3 4 5 ";
string newText = oldText
.Replace(" ", " " + (char)22 )
.Replace( (char)22 + " ", "" )
.Replace( (char)22 + "", "" );
Assert.That( newText, Is.EqualTo( " 1 2 3 4 5 " ) );
문자열을 만들 수 있습니다.RemoveDoubleSpaces()와 같은 메서드가 있는 확장자 파일입니다.
StringsExtensions.cs
public static string RemoveDoubleSpaces(this string value)
{
Regex regex = new Regex("[ ]{2,}", RegexOptions.None);
value = regex.Replace(value, " ");
// this removes space at the end of the value (like "demo ")
// and space at the start of the value (like " hi")
value = value.Trim(' ');
return value;
}
그런 다음 다음 다음과 같이 사용할 수 있습니다.
string stringInput =" hi here is a demo ";
string stringCleaned = stringInput.RemoveDoubleSpaces();
제안된 솔루션을 살펴보았지만, 제 경우에 허용되는 공백 문자의 혼합을 처리할 수 있는 솔루션을 찾을 수 없었습니다. 예:
Regex.Replace(input, @"\s+", " ")예를 들어, 줄 바꿈이 공백과 혼합된 경우, 줄 바꿈을 먹을 것입니다.\n \n시퀀스가 다음으로 대체됩니다.Regex.Replace(source, @"(\s)\s+", "$1")그것은 공백 첫 글자에 의존할 것이며, 다시 당신의 줄 바꿈을 먹을 수도 있다는 것을 의미합니다.Regex.Replace(source, @"[ ]{2,}", " ")예를 들어 공백 문자가 혼합된 경우 올바르게 작동하지 않습니다."\t \t "
완벽하지는 않지만, 저에게 빠른 해결책은 다음과 같습니다.
Regex.Replace(input, @"\s+",
(match) => match.Value.IndexOf('\n') > -1 ? "\n" : " ", RegexOptions.Multiline)
아이디어는 - 줄 바꿈이 공백과 탭 위에서 승리한다는 것입니다.
이렇게 하면 윈도우 라인 파손을 올바르게 처리할 수는 없지만, 윈도우 라인 파손 작업에도 쉽게 적응할 수 있습니다. 정규식을 잘 모르기 때문에 단일 패턴에 맞는 것이 가능할 수도 있습니다.
다음 코드는 단일 공간으로 여러 공간을 모두 제거합니다.
public string RemoveMultipleSpacesToSingle(string str)
{
string text = str;
do
{
//text = text.Replace(" ", " ");
text = Regex.Replace(text, @"\s+", " ");
} while (text.Contains(" "));
return text;
}
언급URL : https://stackoverflow.com/questions/206717/how-do-i-replace-multiple-spaces-with-a-single-space-in-c
'programing' 카테고리의 다른 글
| 시작 시 단일 양식 숨기기 (0) | 2023.05.09 |
|---|---|
| 문자열의 마지막 단어 바꾸기 - C# (0) | 2023.05.09 |
| PEM 인코딩 인증서에서 SSL 인증서 만료 날짜를 확인하는 방법은 무엇입니까? (0) | 2023.05.09 |
| MongoDB: 무조건적인 업데이트? (0) | 2023.05.09 |
| Azure 로그인 자격 증명을 사용하여 FTP를 통해 Azure 웹 사이트에 연결 (0) | 2023.05.09 |