如何在Delphi XE6中移除字符串的所有空白字符?
Delphi XE6 移除字符串所有空白字符
之前使用的代码仅能移除普通空格,无法处理制表符、换行符等其他空白字符:
function RemoveWhitespace(S: string): string; begin Result := StringReplace(S, ' ', '', [rfReplaceAll]); end;
要移除所有Unicode定义的空白字符,这里提供两种实用实现:
高效遍历筛选法
这种方法性能最优,适合处理大量字符串:
uses SysUtils; function RemoveAllWhitespace(const S: string): string; var I: Integer; Ch: Char; begin Result := ''; SetLength(Result, Length(S)); // 预分配内存避免频繁扩容 I := 0; for Ch in S do begin if not TCharacter.IsWhiteSpace(Ch) then begin Inc(I); Result[I] := Ch; end; end; SetLength(Result, I); end;
正则表达式替换法
如果更看重代码简洁性,可以用正则匹配所有空白字符:
uses RegularExpressions; function RemoveAllWhitespace(const S: string): string; begin Result := TRegEx.Replace(S, '\s', '', [roReplaceAll]); end;
注意事项
TCharacter.IsWhiteSpace会识别所有符合Unicode标准的空白字符,包括空格、制表符、换行符、回车符等,覆盖范围比单纯替换空格全面得多。- 遍历法的执行效率远高于正则表达式,处理大字符串时差异更明显。
内容的提问来源于stack exchange,提问作者Vlastimil Burián
相关产品推荐
相关产品推荐

