How to Split a String into Segments of N Characters

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

var str = 'abcdefghijkl';console.log(str.match(/.{1,3}/g));

Split a string into N equal parts?

import textwrap
print(textwrap.wrap("123456789", 2))
#prints ['12', '34', '56', '78', '9']

Note: be careful with whitespace etc - this may or may not be what you want.

"""Wrap a single paragraph of text, returning a list of wrapped lines.

Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
"""

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

Try the below code:

var foo = "foofaafoofaafoofaafoofaafoofaa";console.log( foo.match(/.{1,3}/g) );

Split string every n characters

Once Kotlin 1.2 is released, you can use the chunked function that is added to kotlin-stdlib by the KEEP-11 proposal. Example:

val chunked = myString.chunked(2)

You can already try this with Kotlin 1.2 M2 pre-release.


Until then, you can implement the same with this code:

fun String.chunked(size: Int): List<String> {
val nChunks = length / size
return (0 until nChunks).map { substring(it * size, (it + 1) * size) }
}

println("abcdef".chunked(2)) // [ab, cd, ef]

This implementation drops the remainder that is less than size elements. You can modify it do add the remainder to the result as well.

Split large string in n-size chunks in JavaScript

You can do something like this:

"1234567890".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "90"]

The method will still work with strings whose size is not an exact multiple of the chunk-size:

"123456789".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "9"]

In general, for any string out of which you want to extract at-most n-sized substrings, you would do:

str.match(/.{1,n}/g); // Replace n with the size of the substring

If your string can contain newlines or carriage returns, you would do:

str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring

As far as performance, I tried this out with approximately 10k characters and it took a little over a second on Chrome. YMMV.

This can also be used in a reusable function:

function chunkString(str, length) {
return str.match(new RegExp('.{1,' + length + '}', 'g'));
}

How to split a string into chunks per number of characters and delimiter?

You could use functools.reduce to accomplish this.

import functools

def splitter(s, n):
def helper(acc, v):
tmp1 = acc[-1]
tmp2 = len(tmp1)
if tmp2 >= n or tmp2 + len(v) >= n:
acc.append(v)
else:
acc[-1] = tmp1 + ',' + v

return acc

tmp1 = s.split(',')
if len(tmp1) == 1:
return tmp1

return list(functools.reduce(helper, tmp1[1:], [tmp1[0]]))

Splitting a string into chunks of a certain size

static IEnumerable<string> Split(string str, int chunkSize)
{
return Enumerable.Range(0, str.Length / chunkSize)
.Select(i => str.Substring(i * chunkSize, chunkSize));
}

Please note that additional code might be required to gracefully handle edge cases (null or empty input string, chunkSize == 0, input string length not divisible by chunkSize, etc.). The original question doesn't specify any requirements for these edge cases and in real life the requirements might vary so they are out of scope of this answer.

Splitting a string at every n-th character

You could do it like this:

String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));

which produces:

[123, 456, 789, 0]

The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))



Related Topics



Leave a reply



Submit