我该怎么做才能实现如图所示的右侧输出?请注意,稍后会有许多数据具有这种不一致的对齐方式,是否有任何方法可以循环所有文本以及经过调整的对齐方式,如图像右侧所示?
您可以使用Regex将单个空格替换多个空格(2个或更多,包括制表符)。例如,
var result = Regex.Replace(str,"[\t ]{2,}"," ");
空白的常见形式可以分为
在上述情况下,您似乎需要用单个空格字符替换所有空格(2个或更多)和Tab字符(并忽略换行/返回字符)。为此,您可以使用正则表达式,如上面的代码所示
简短回答,使用Trim()或TrimEnd,但这是我使用Nuget包完成任务的方式,如果您不想使用Nuget包,可以将其转换为string.Split():
Nuget包装:DataJuggler.Core.UltimateHelper(.Net Framework)
[DataJuggler.UltimateHelper.Core(.Net Core)
显示.Net框架
// source input
string inputFileText = "blah blah blah blah blah " + Environment.NewLine + "blah blah blah blah blah";
// parse the lines
List<TextLine> lines = WordParser.GetTextLines(inputFileText);
// If the lines collection exists and has one or more items
if (ListHelper.HasOneOrMoreItems(lines))
{
// Iterate the collection of TextLine objects
foreach (TextLine line in lines)
{
// Get the words
List<Word> words = WordParser.GetWords(line.Text);
}
}
然后,您可以对每一行进行所需的操作,并且每一行都包含单词列表(字符串文本)。
这里是Nuget包使用的代码,如果您愿意复制它:
public static List<TextLine> GetTextLines(string sourceText)
{
// initial value
List<TextLine> textLines = new List<TextLine>();
// typical delimiter characters
char[] delimiterChars = Environment.NewLine.ToCharArray();
// local
int counter = -1;
// verify the sourceText exists
if (!String.IsNullOrEmpty(sourceText))
{
// Get the list of strings
string[] linesOfText = sourceText.Split(delimiterChars);
// now iterate the strings
foreach (string lineOfText in linesOfText)
{
// local
string text = lineOfText;
// increment the counter
counter++;
// add every other row
if ((counter % 2) == 0)
{
// Create a new TextLine
TextLine textLine = new TextLine(text);
// now add this textLine to textLines collection
textLines.Add(textLine);
}
}
}
// return value
return textLines;
}
public static List<Word> GetWords(string sourceText, char[] delimeters = null, bool allowEmptyStrings = false)
{
// initial value
List<Word> words = new List<Word>();
// typical delimiter characters
char[] delimiterChars = { ' ','-','/', ',', '.', '\t' };
// if the delimter exists
if (NullHelper.Exists(delimeters))
{
// use these delimters
delimiterChars = delimeters;
}
// verify the sourceText exists
if (!String.IsNullOrEmpty(sourceText))
{
// Get the list of strings
string[] strings = sourceText.Split(delimiterChars);
// now iterate the strings
foreach(string stringWord in strings)
{
// verify the word is not an empty string or a space
if ((allowEmptyStrings) || (TextHelper.Exists(stringWord)))
{
// Create a new Word
Word word = new Word(stringWord);
// now add this word to words collection
words.Add(word);
}
}
}
// return value
return words;
}