在 .NET 中以换行符分割字符串的最简单方法?

Easiest way to split a string on newlines in .NET?(在 .NET 中以换行符分割字符串的最简单方法?)
本文介绍了在 .NET 中以换行符分割字符串的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 .NET 中将字符串拆分为换行符,而我知道拆分字符串的唯一方法是使用 拆分 方法.但是,这不允许我(轻松)在换行符上拆分,那么最好的方法是什么?

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?

推荐答案

要对字符串进行拆分,您需要使用带字符串数组的重载:

To split on a string you need to use the overload that takes an array of strings:

string[] lines = theText.Split(
    new string[] { Environment.NewLine },
    StringSplitOptions.None
);


如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能.这将在任一类型的换行符上正确拆分,并在文本中保留空行和间距:


If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:

string[] lines = theText.Split(
    new string[] { "
", "
", "
" },
    StringSplitOptions.None
);

这篇关于在 .NET 中以换行符分割字符串的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)