简体   繁体   中英

string.split for alternating characters in c#

I know this is going to be an easy answer but I am new to C#. There is a lot of answers on for different types of splits, but I cannot find one for this problem. I am trying to split a string into two by alternating characters.

The example would be: string example = "stackoverflow" and the output would be "sakvrlo" and "tcoefo" .

If it is an odd number of characters it does not matter if the two new strings are of different lengths.

Thanks!

StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();

string source = "some string to split";

// ALTERNATE: if you want an explicitly typed char[]
// char[] source = "some string to split".ToCharArray();

for( int i = 0; i < source.Length; i++ )
{
   if( i % 2 == 0 )
   {
        sb1.Append( source[i] );
   }
   else
   {
        sb2.Append( source[i] );
   } 
}

Notes:

  • There is no BCL method that I am aware of that does this automatically (eg string.SplitAlternating() .

  • Since the size of the string is known, the StringBuilders can be initialized with a fixed buffer size.

  • LINQ solution (@usr's answer) is cleaner but slower (if it matters, which is probably rarely).

  • If performance truly does matter, the fastest way is probably to obtain a pointer to the start of the original char array and iterate by incrementing two separate pointers created by two char arrays declared using stacalloc . Subsequently, those two char arrays can then be passed as an argument to string's constructor. Make sure to append null terminators.

var a = new string(source.Where((c,i) => i % 2 == 0).ToArray());
var b = new string(source.Where((c,i) => i % 2 != 0).ToArray());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM