2014-06-12 3 views
0

모든 더블 스페이스를 단일 스페이스로 바꾸려고합니다.더블 스페이스가있는 String.Replace가 실패합니다.

그러나, 이것은 다음과 같은 경우에 작동하지 않습니다

Dim s As String = "SECTIONSHOMESEARCHSKIP TO CONTENTSKIP TO NAVIGATIONVIEW MOBILE VERSION SETTINGS Loading... MAGAZINE JUNE 11, 2014 Photo Credit Jude Edginton for The New York Times Continue reading the main storyContinue reading the main story Talk Intervie..." 

s = s.Replace(" ", " ") 

Debug.Assert(InStr(s, " ", CompareMethod.Binary) = 0)'Assertion occurs 

아무도 볼 수 있나요 잘못 여기에 무엇을 갈 수

?

감사합니다.

+0

에 차이 중 일부는 너무 3-2 + 1 = 2 단지 두 번 교체 실행, 사실 3 개 공간에 있습니다. 처음부터 길이가 259에서 247로 바뀌어 작동합니다. 또는'Do While s.Contains ("") // Replace // End Loop' – Plutonix

답변

1

do 
    s = s.Replace(" ", " ") 
loop until while InStr(s, " ", CompareMethod.Binary)=0 
+0

음, 나는 그것을 좋아하지 않지만, 가장 빠릅니다. – Steve

2

길이가 2보다 큰 공백이 있으므로 작동하지 않습니다.

당신은 String.SplitString.Join + StringSplitOptions.RemoveEmptyEntries와 함께 사용할 수 : 2 개 이상의 공백 뭔가가 첫 번째 반복에서 수행되지 않기 때문에 당신은, 루프 필요

s = String.Join(" ", s.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)) 
1

당신은 할 수 Regex.Replace를 사용하십시오.

Dim s As String = "SECTIONSHOMESEARCHSKIP TO CONTENTSKIP TO NAVIGATIONVIEW MOBILE VERSION SETTINGS Loading... MAGAZINE JUNE 11, 2014 Photo Credit Jude Edginton for The New York Times Continue reading the main storyContinue reading the main story Talk Intervie..." 
Dim r = Regex.Replace(s, "[ ]{2,}", " "c) 
Console.WriteLine(r) 

=> SECTIONSHOMESEARCHSKIP TO CONTENTSKIP TO NAVIGATIONVIEW MOBILE VERSION SETTINGS Loading... MAGAZINE JUNE 11, 2014 Photo Credit Jude Edginton for The New York Times Continue reading the main storyContinue reading the main story Talk Intervie... 

Regex.Replace "[ ]{2,}", " "c은 두 개 또는 그 이상의 공백을 찾아 하나의 공백 문자로 바꾸는 것을 의미합니다.

편집 나는 정규식과 팀 Schmelter에 의해 제안 된 string.Join/분할을 기반으로 솔루션 사이의 성능 차이가 무엇인지 궁금했다. 선을 분리하고 배열을 만든 다음 모든 것을 다시 합치는 데 필요한 모든 작업에도 불구하고 제안 된 방식의 Tim이 빠릅니다.

Dim sw = new Stopwatch() 
sw.Start() 
for i = 0 to 1000000 
Dim r = Regex.Replace(s, "[ ]{2,}", " "c) 
Next 
sw.Stop 
Console.WriteLine("Regex:" & sw.ElapsedMilliseconds) 

sw = new Stopwatch() 
sw.Start() 
for i = 0 to 1000000 
    s = String.Join(" ", s.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)) 
Next 
sw.Stop 
Console.WriteLine("Split/Join: " & sw.ElapsedMilliseconds) 

출력은 내 PC

Regex: 6265 
Split/Join: 3745 
관련 문제