![](/img/trans.png)
[英]In C# how to search a text for words in a array and store in a second array
[英]How to split text value into array with words in C#?
是否有可能將txtSearche
值保存在分割成單獨單詞的數組中?
txtSearche = "put returns between paragraphs";
這樣的事情:
StringBuilder sb = new StringBuilder(txtSearche);
array1 = sb[1] = put
array2 = sb[2] = returns
array3 = sb[3]
array4 = sb[4]
array5 = sb[5]
怎么做對嗎?
是試試這個:
string[] words = txtSearche.Split(' ');
這會給你:
words[0] = put
words[1] = returns
words[2] = between
words[3] = paragraphs
編輯:同樣如下面Adkins所提到的,單詞數組將被創建為提供的字符串所需的任何大小。 如果您希望列表具有動態大小,我會說使用List wordList = words.ToList();將數組放入列表中。
編輯:Nakul分割一個或多個空格,只需將它們作為參數添加到Split()
方法中,如下所示:
txtSearche.Split(new string[] { " ", " ", " " }, StringSplitOptions.None);
或者您可以通過使用StringSplitOptions.RemoveEmptyEntries
枚舉來簡單地將其拆分為單個空格並忽略由連續空格引起的空白條目
txtSearche.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
你可以使用String.Split
。
以上都不適用於多個空格或新行 !!!
以下是它們的作用:
string text = "hi!\r\nI am a wonderful56 text... \r\nyeah...";
string[] words =Regex.Split(text, @"\s+", RegexOptions.Singleline);
如果你需要刪除省略號,那么需要更多的處理,我也可以給你。
UPDATE
事實上這更好:
string text = "hi!\r\nI am a wonderful56 text... \r\nyeah...";
MatchCollection matches = Regex.Matches(text, @"[\w\d_]+", RegexOptions.Singleline);
foreach (Match match in matches)
{
if(match.Success)
Console.WriteLine(match.Value);
}
產出 :
嗨,我是一個很棒的文字,是的
StringBuilder sb = new StringBuilder(txtSearche);
var result = sb.Tostring().Split(' ');
如果你想要一個更完整的解決方案而不是完全擔心性能,你可以使用這個單線程序來處理標點符號等,並為你提供一系列單詞。
string[] words = Regex.Replace(Regex.Replace(text, "[^a-zA-Z0-9 ]", " "), @"\s+", " ").Split(' ');
private void button1_Click(object sender, EventArgs e)
{
string s = textBox1.Text;
string[] words = s.Split(' ');
textBox2.Text = words[0];
textBox3.Text = words[1];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.