Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 4533a5e

Browse files
committed
Add CollapseWhitespace string extension
1 parent 5cf6773 commit 4533a5e

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/ServiceStack.Text/StreamExtensions.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System;
55
using System.Collections.Generic;
66
using System.IO;
7+
using System.Text;
78
using ServiceStack.Text;
89

910
namespace ServiceStack
@@ -242,5 +243,29 @@ private static byte[] ReadExactlyFast(Stream fromStream, byte[] intoBuffer, int
242243
}
243244
return intoBuffer;
244245
}
246+
247+
public static string CollapseWhitespace(this string str)
248+
{
249+
if (str == null)
250+
return null;
251+
252+
var sb = new StringBuilder();
253+
254+
var lastChar = (char)0;
255+
for (var i = 0; i < str.Length; i++)
256+
{
257+
var c = str[i];
258+
if (c < 32) continue; // Skip all these
259+
if (c == 32)
260+
{
261+
if (lastChar == 32)
262+
continue; // Only write one space character
263+
}
264+
sb.Append(c);
265+
lastChar = c;
266+
}
267+
268+
return sb.ToString();
269+
}
245270
}
246271
}

0 commit comments

Comments
 (0)