Как сначала «Разделить строку на массив», затем «Добавить что-то в этот массив»? ||Консольное приложение C # - PullRequest
0 голосов
/ 17 октября 2019

Я пытаюсь создать программу, которая разбивает строку на массив, а затем добавляет к этому массиву.

Разделение строки работает, но добавление в массив действительно приводит к драке.

//here i create the text
string text = Console.ReadLine();
Console.WriteLine();

//Here i split my text to elements in an Array 
var punctuation = text.Where(Char.IsPunctuation).Distinct().ToArray();
var words = text.Split().Select(x => x.Trim(punctuation));

//here i display the splitted string
foreach (string x in words)
{
  Console.WriteLine(x);
}

//Here a try to add something to the Array
Array.words(ref words, words.Length + 1);
words[words.Length - 1] = "addThis";

//I try to display the updated array
foreach (var x in words)
{
  Console.WriteLine(x);
}

//Here are the error messages |*error*|
Array.|*words*|(ref words, words.|*Length*| + 1);
words[words.|*Length*| - 1] = "addThis";

«Массив» не содержит определения для «слов»

Не содержит определения для длины

Не содержит определения для длины * /

Ответы [ 2 ]

2 голосов
/ 17 октября 2019

Преобразовать IEnumerable в список:

var words = text.Split().Select(x => x.Trim(punctuation)).ToList();

Когда это список, вы можете позвонить Add

words.Add("addThis");
0 голосов
/ 17 октября 2019

Технически, если вы хотите разделить на пунктуацию , я предлагаю 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():

    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
...