我使用這種方法從字串中拆分單詞,但\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;
}
uj5u.com熱心網友回復:
好吧,只用空格string.Split()分割

更新:
使用正則運算式并保留行字符的另一種解決方案:
string str = "my test\r\n string\n is here";
var wordsByRegex = Regex.Split(str, @"(?= ). ?(\r|\n|\r\n)?").ToList();

uj5u.com熱心網友回復:
小提琴
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();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/398775.html
