如何在C#中将文本值拆分为带有单词的数组? [英] How to split text value into array with words in C#?

查看:67
本文介绍了如何在C#中将文本值拆分为带有单词的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将txtSearche的值保存在拆分为单独单词的数组中?

Is it possible to save value of txtSearche in array splitted into seperate words?

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]

如何纠正?

推荐答案

是的,请尝试以下操作:

Yes try this:

string[] words = txtSearche.Split(' ');

这将为您提供:

words[0]   = put
words[1]   = returns
words[2]   = between
words[3]   = paragraphs

编辑:也正如下面的 Adkins 所述,单词数组将根据所提供的字符串所需的大小创建.如果您希望列表具有动态大小,则可以使用List wordList = words.ToList();

Also as Adkins mentions below, the words array will be created to whatever size is needed by the string that is provided. If you want the list to have a dynamic size I would say drop the array into a list using List wordList = words.ToList();

Nakul 可以拆分一个或多个空格,只需将它们作为参数添加到Split()方法中,如下所示:

Nakul to split by one space or more, just add them as parameters into the Split() method like below:

txtSearche.Split(new string[] { " ", "  ", "   " }, StringSplitOptions.None);

或者您也可以像这样使用StringSplitOptions.RemoveEmptyEntries枚举,让它简单地分隔一个空格并忽略由连续空格引起的空白条目

or you can tell it simply to split by a single space and ignore entries that are blank, caused by consecutive spaces, by using the StringSplitOptions.RemoveEmptyEntries enum like so

txtSearche.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

这篇关于如何在C#中将文本值拆分为带有单词的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆