我需要逐个字符地读取字符串,并构建一个新字符串作为输出.
在C#中执行此操作的最佳方法是什么?
使用StringBuilder?使用一些writer/stream?
请注意,不会有I/O操作 - 这严格来说是内存中的转换.
如果在编译时无法确定字符串的大小并且它也可能相对较大,则应使用StringBuilderfor进行连接,因为它的作用类似于可变字符串.
var input = SomeLongString;
// may as well initialize the capacity as well
// as the length will be 1 to 1 with the unprocessed input.
var sb = new StringBuilder( input.Length );
foreach( char c in input )
{
sb.Append( Process( c ) );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |