Answer the question
In order to leave comments, you need to log in
How to create a string from an array with a delimiter?
I have an array:
string[] sentence = new string[] { "Привет", "меня", "зовут", "*", "Мой", "возраст", "таков" };
var name = "Привет меня зовут"
var age = "Мой возраст таков"
Answer the question
In order to leave comments, you need to log in
1. Hold the extension I just wrote (tested it to behave almost like string.Split)
The code is certainly not perfect, but it works
public static class ArrayExtensions
{
public static List<List<T>> Split<T>(this IEnumerable<T> array, T separator, IEqualityComparer<T>? equalityComparer = null)
{
equalityComparer ??= EqualityComparer<T>.Default;
var parts = new List<List<T>>();
var currentPart = new List<T>();
foreach (var element in array)
{
var isSeparator = equalityComparer.Equals(element, separator);
if (isSeparator)
{
parts.Add(currentPart);
currentPart = new List<T>();
}
else
{
currentPart.Add(element);
}
}
parts.Add(currentPart);
return parts;
}
}
var array = new [] { "Привет", "меня", "зовут", "*", "Мой", "возраст", "таков" };
var parts = array.Split("*").Select(x => string.Join(' ', x)).ToArray();
var name = parts[0];
var age = parts[1];
IndexOf method of an array -> find out the separator index.
The string.Join() method -> glue the array of strings into one string through a delimiter.
var words = new[] { "Привет", "меня", "зовут", "*", "Мой", "возраст", "таков" };
var variables = new Dictionary<string, string>()
{
{"name", string.Empty},
{"age", string.Empty}
};
var items = words.Select((word, index) => new
{
Item = word,
Index = index,
Group = words.Skip(index)
.Select((wordFind, indexFind) => new
{
Item = wordFind,
Index = indexFind + index
})
.FirstOrDefault(wordFilter => wordFilter.Item.Equals("*"))
}).GroupBy(wordGroup => wordGroup.Group?.Index);
foreach (var item in items)
{
var groupped = string.Join(" ",
item.Select(word => word.Item)
.Where(word => !word.Equals("*")));
var key = variables.Where(keyVariable => keyVariable.Value.Equals(string.Empty))
.Select(keyVariable => keyVariable.Key).FirstOrDefault();
if (key != null && variables.ContainsKey(key))
{
variables[key] = groupped;
}
}
Debug.WriteLine(
string.Join("\n", variables.Select(wordsObject =>
$"key: {wordsObject.Key}, value: {wordsObject.Value}")));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question