I use this method for splitting words from string, but \n
doesn't consider. How can I solve it?
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;
}
CodePudding user response:
Well, string.Split()
splits by white-spaces only
UPDATE:
Another solution with regex and keeping line characters:
string str = "my test\r\n string\n is here";
var wordsByRegex = Regex.Split(str, @"(?= ). ?(\r|\n|\r\n)?").ToList();
CodePudding user response:
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();
}
}
}