문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top