繁体   English   中英

从字符串中拆分单词

[英]Split word from string

我使用这种方法从字符串中拆分单词,但\n不考虑。 我该如何解决?

public string SplitXWord(string text, int wordCount)
{
    string output = "";
    IEnumerable<string> words = text.Split().Take(wordCount);
    foreach (string word in words)
    {
        output += " " + word;
    }

    return output;
}

好吧, string.Split()仅按空格拆分

https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=net-6.0

拆分用于将分隔字符串拆分为子字符串。 您可以使用字符数组或字符串数组来指定零个或多个分隔字符或字符串。 如果未指定分隔字符,则字符串在空白字符处拆分。

粗体是我的。

到目前为止一切顺利, string.Split()空格' '制表'\t'新行'\n'回车'\r'等上分割:

Console.Write(string.Join(", ", "a\nb\rc\td e".Split()));

生产

a, b, c, d, e

如果你想分割你的牛分隔符,你应该提供它们:

Console.Write(string.Join(", ", "a\nb\rc\td e".Split(new char[] {' ', '\t'})));

请注意\r\n被保留,当在' ''t'上拆分时

a
b
c, d, e

因此,您的方法似乎应该是这样的:

using System.Linq;

...

//DONE: static - we don't want this here
public static string SplitXWord(string text, int wordCount) {
  //DONE: don't forget about degenerated cases
  if (string.IsNullOrWhiteSpace(text) || wordCount <= 0)
    return "";

  //TODO: specify delimiters on which you want to split
  return string.Join(" ", text
    .Split(
       new char[] { ' ', '\t' },  
       wordCount + 1, 
       StringSplitOptions.RemoveEmptyEntries)
    .Take(wordCount));
}

使用 Split 方法的重载,该方法接受字符分隔符数组并清除空条目

string str = "my test \n\r string \n is here"; 
string[] words = str.Split(new []{' ', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);

在此处输入图像描述


更新:

使用正则表达式并保留行字符的另一种解决方案:

string str = "my test\r\n string\n is here";
var wordsByRegex = Regex.Split(str, @"(?= ).+?(\r|\n|\r\n)?").ToList();

在此处输入图像描述

小提琴

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp17
{
    class Program
    {
        static void Main(string[] args)
        {
            string myStr = "hello my friend \n whats up \n bro";
            string[] mySplitStr = myStr.Split("\n");
            mySplitStr.ToList().ForEach(str=>{
                Console.WriteLine(str);
                //to remove the white spaces 
                //Console.WriteLine(str.Replace(" ",""));
            });
            Console.ReadLine();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM