Frage

Maybe this is a silly question. But I haven't found an answer yet. I've got some strings. I would like to concatenate them and then split the resulting string in a different moment. I would like to know if there's something available inside the .NET Framework. The Join and Split methods of String work quite well. The problem is to escape the separator character.

For example, I would like to use the "@" as separator character. If I have "String1", "Str@ing2" and "String3", I would like to obtain "String1@Str@@ing2@String3".

Is there something that does what I need or do I have to write my own function?

Thank you.

War es hilfreich?

Lösung

Just escape the separator on the way in.

var inputs = ["String1", "Str@ing2", "String3"];
var joined = string.Join(inputs.Select(i => i.Replace("@", "@@"));

You can then split on single @ chars.

var split = Regex.Split(joined, "(?<!@)@(?!@)");

This uses zero-width negative lookbehind/lookahead patterns to assert the character before and after the @ is not another @. You should run some tests on cases where @ is at the start or end of your input strings however.

Andere Tipps

Call .Replace("@", "@@") on each string before passing them to .Join

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top