Splitting a String/Number Every Nth Character/Number

Splitting a string / number every Nth Character / Number?

If you have to do that in many places in your code you can create a fancy extension method:

static class StringExtensions {

public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {
if (s == null)
throw new ArgumentNullException(nameof(s));
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", nameof(partLength));

for (var i = 0; i < s.Length; i += partLength)
yield return s.Substring(i, Math.Min(partLength, s.Length - i));
}

}

You can then use it like this:

var parts = "32427237".SplitInParts(3);
Console.WriteLine(String.Join(" ", parts));

The output is 324 272 37 as desired.

When you split the string into parts new strings are allocated even though these substrings already exist in the original string. Normally, you shouldn't be too concerned about these allocations but using modern C# you can avoid this by altering the extension method slightly to use "spans":

public static IEnumerable<ReadOnlyMemory<char>> SplitInParts(this String s, Int32 partLength)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", nameof(partLength));

for (var i = 0; i < s.Length; i += partLength)
yield return s.AsMemory().Slice(i, Math.Min(partLength, s.Length - i));
}

The return type is changed to public static IEnumerable<ReadOnlyMemory<char>> and the substrings are created by calling Slice on the source which doesn't allocate.

Notice that if you at some point have to convert ReadOnlyMemory<char> to string for use in an API a new string has to be allocated. Fortunately, there exists many .NET Core APIs that uses ReadOnlyMemory<char> in addition to string so the allocation can be avoided.

Split string every nth character from the right?

You can adapt the answer you linked, and use the beauty of mod to create a nice little one-liner:

>>> s = '1234567890'
>>> '/'.join([s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'1/234/567/890'

and if you want this to auto-add the dot for the cases like your first example of:

s = '100243'

then you can just add a mini ternary use or as suggested by @MosesKoledoye:

>>> '/'.join(([s[0:len(s)%3] or '.']) + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'./100/243'

This method will also be faster than reversing the string before hand or reversing a list.

split-string-every-nth-character with nth+1 separator '0'

You can use a regular expression with capture groups.

import re

instr = '01110100001101001001110100'
outlist = list(sum(re.findall(r'(\d{8})(\d)', instr), ()))

print(outlist)

re.findall() returns a list of tuples, list(sum(..., ()) flattens it into a single list.

Split a string, at every nth position, with JavaScript?

Try the below code:

var foo = "foofaafoofaafoofaafoofaafoofaa";

console.log( foo.match(/.{1,3}/g) );

Splitting a Python string every nth character iterating backwards

Just add [::-1] in two places in your code:

' '.join(binaryString[::-1][i:i+4] for i in range(0, len(binaryString), 4))[::-1]

p.s [::-1] reverse the string, so you just reverse it, add spaces in your way and then reverse again to proper initial order.

How can I split a string into segments of n characters?

var str = 'abcdefghijkl';

console.log(str.match(/.{1,3}/g));

How to split a text into characters and get a text including every nth character ? (Maybe in Excel)

In excel sheet, with ExcelO365 you can use Sequence() formula with MID() function like-

=TEXTJOIN("",TRUE,MID(A1,SEQUENCE(LEN(A1),,1,5),1))

Sample Image

For second one just make Start Number parameter of Sequence() formula to 2 like

=TEXTJOIN("",TRUE,MID(A1,SEQUENCE(LEN(A1),,2,5),1))


Related Topics



Leave a reply



Submit