我需要在. net中将字符串分割为换行符,我所知道的分割字符串的唯一方法是使用split方法。然而,这将不允许我(容易)在换行上分裂,那么最好的方法是什么?
当前回答
使用StringReader怎么样?
using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
string line = reader.ReadLine();
}
其他回答
好吧,实际上拆分应该做:
//Constructing string...
StringBuilder sb = new StringBuilder();
sb.AppendLine("first line");
sb.AppendLine("second line");
sb.AppendLine("third line");
string s = sb.ToString();
Console.WriteLine(s);
//Splitting multiline string into separate lines
string[] splitted = s.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
// Output (separate lines)
for( int i = 0; i < splitted.Count(); i++ )
{
Console.WriteLine("{0}: {1}", i, splitted[i]);
}
对于字符串变量s:
s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)
这使用了您的环境对行结束符的定义。在Windows上,行结束符是CR-LF(回车,换行)或c#的转义字符\r\n。
这是一个可靠的解决方案,因为如果您用String重新组合这些行。Join,这等于你原来的字符串:
var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
var reconstituted = String.Join(Environment.NewLine,lines);
Debug.Assert(s==reconstituted);
不要做什么:
使用StringSplitOptions。RemoveEmptyEntries,因为这将破坏Markdown等标记,其中空行具有语法目的。 在分隔符上拆分新char[]{环境。因为在Windows上,这将为每一行创建一个空字符串元素。
我只是想加上我的二进制,因为这个问题的其他解决方案不属于可重用代码分类,不方便。
下面的代码块扩展了string对象,以便在处理字符串时可以使用它作为一个自然的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.ObjectModel;
namespace System
{
public static class StringExtensions
{
public static string[] Split(this string s, string delimiter, StringSplitOptions options = StringSplitOptions.None)
{
return s.Split(new string[] { delimiter }, options);
}
}
}
你现在可以从任何字符串中使用.Split()函数,如下所示:
string[] result;
// Pass a string, and the delimiter
result = string.Split("My simple string", " ");
// Split an existing string by delimiter only
string foo = "my - string - i - want - split";
result = foo.Split("-");
// You can even pass the split options parameter. When omitted it is
// set to StringSplitOptions.None
result = foo.Split("-", StringSplitOptions.RemoveEmptyEntries);
要在换行符上进行分割,只需传递“\n”或“\r\n”作为分隔符参数。
评论:如果微软能实现这个重载就太好了。
Regex也是一个选项:
private string[] SplitStringByLineFeed(string inpString)
{
string[] locResult = Regex.Split(inpString, "[\r\n]+");
return locResult;
}
愚蠢的回答:写到一个临时文件,这样你就可以使用可敬的 文件。readline
var s = "Hello\r\nWorld";
var path = Path.GetTempFileName();
using (var writer = new StreamWriter(path))
{
writer.Write(s);
}
var lines = File.ReadLines(path);
推荐文章
- 如何创建数组。包含不区分大小写的字符串数组?
- 检查字符串是否包含字符串列表中的元素
- 我如何在c++中创建一个随机的字母数字字符串?
- 最好的方法在asp.net强制https为整个网站?
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- 将字符串转换为System.IO.Stream
- Java中的split()方法对点(.)不起作用。
- 我如何检查如果一个变量是JavaScript字符串?
- 如何显示有两个小数点后的浮点数?
- 如何从枚举中选择一个随机值?
- 在Lua中拆分字符串?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock