【问题标题】:Split word from string从字符串中拆分单词
【发布时间】:2021-12-28 14:59:12
【问题描述】:

我使用这种方法从字符串中拆分单词,但\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;
}

【问题讨论】:

标签: c# .net string split


【解决方案1】:

好吧,string.Split() 仅由 空格 分割

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

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

粗体是我的。

到目前为止一切顺利,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));
}

【讨论】:

    【解决方案2】:

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

    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();
    

    【讨论】:

    • 我想要的结果是:[0] = "my" [1] = "test \n" ....
    • @RebinEsmaily 请更新您的帖子以包含一个最小的可重现示例和预期输出。不要在 cmets 中传达这样的更改,不是每个人都会看到或理解您的要求。
    【解决方案3】:

    fiddle

    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();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 2014-06-09
      相关资源
      最近更新 更多