如何首先';将字符串拆分为数组';然后';向该数组添加一些内容';?| |C#控制台应用程序

如何首先';将字符串拆分为数组';然后';向该数组添加一些内容';?| |C#控制台应用程序,c#,arrays,string,split,resize,C#,Arrays,String,Split,Resize,我试图创建一个程序,将字符串拆分为数组,然后添加 到那个数组 拆分字符串是可行的,但添加到数组中确实会产生错误 战斗 “数组”不包含“单词”的定义 不包含长度的定义 不包含长度定义*/将IEnumerable转换为列表: var words = text.Split().Select(x => x.Trim(punctuation)).ToList(); 一旦它成为一个列表,您就可以调用Add words.Add("addThis"); 从技术上讲,如果您想在标点符号上拆分,我建议使用

我试图创建一个程序,将字符串拆分为数组,然后添加 到那个数组

拆分字符串是可行的,但添加到数组中确实会产生错误 战斗

“数组”不包含“单词”的定义

不包含长度的定义


不包含长度定义*/

将IEnumerable转换为列表:

var words = text.Split().Select(x => x.Trim(punctuation)).ToList();
一旦它成为一个列表,您就可以调用
Add

words.Add("addThis");

从技术上讲,如果您想在标点符号上拆分,我建议使用
Regex.split
而不是
string.split

  using System.Text.RegularExpressions;

  ...

  string text = 
    @"Text with punctuation: comma, full stop. Apostroph's and ""quotation?"" - ! Yes!";

  var result = Regex.Split(text, @"\p{P}");

  Console.Write(string.Join(Environment.NewLine, result));
结果:

Text with punctuation      # Space is not a punctuation, 3 words combined
 comma
 full stop
 Apostroph                 # apostroph ' is a punctuation, split as required
s and 
quotation



 Yes
如果您想添加一些项目,我建议Linq
Concat()
.ToArray()

但是,您似乎希望提取单词,而不是在拼音上拆分,您可以通过匹配这些单词来完成:

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  string text = 
    @"Text with punctuation: comma, full stop. Apostroph's and ""quotation?"" - ! Yes!";

  string[] words = Regex
    .Matches(text, @"[\p{L}']+") // Let word be one or more letters or apostrophs
    .Cast<Match>()
    .Select(match => match.Value)
    .Concat(new string[] { "addThis"})
    .ToArray();

  Console.Write(string.Join(Environment.NewLine, result));

你的两个问题有很多答案。用了不到30秒的时间显示你想出了使用
数组的方法。单词
?我想你是指
数组。调整大小
,而不是
数组。单词
可能的重复总是使用正确的工具!阵列不是为此而制作的;使用列表!我想我会先试试数组,但我很感激你的回答!谢谢!我将研究Regex和Concat以更好地理解这一点:)
    string text = 

    string[] words = Regex
      .Split(text, @"\p{P}")
      .Concat(new string[] {"addThis"})
      .ToArray();
  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  string text = 
    @"Text with punctuation: comma, full stop. Apostroph's and ""quotation?"" - ! Yes!";

  string[] words = Regex
    .Matches(text, @"[\p{L}']+") // Let word be one or more letters or apostrophs
    .Cast<Match>()
    .Select(match => match.Value)
    .Concat(new string[] { "addThis"})
    .ToArray();

  Console.Write(string.Join(Environment.NewLine, result));
Text
with
punctuation
comma
full
stop
Apostroph's
and
quotation
Yes
addThis