Split String into Smaller Strings by Length Variable

Split String into smaller Strings by length variable

You need to use a loop:

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
for (int index = 0; index < str.Length; index += maxLength) {
yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
}
}

Alternative:

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
int index = 0;
while(true) {
if (index + maxLength >= str.Length) {
yield return str.Substring(index);
yield break;
}
yield return str.Substring(index, maxLength);
index += maxLength;
}
}

2nd alternative: (For those who can't stand while(true))

public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
int index = 0;
while(index + maxLength < str.Length) {
yield return str.Substring(index, maxLength);
index += maxLength;
}

yield return str.Substring(index);
}

Split String into smaller words by length variable in c#

Try this:

string text = "My school Name is stack over flow High school.";
List<string> lines =
text
.Split(' ')
.Aggregate(new [] { "" }.ToList(), (a, x) =>
{
var last = a[a.Count - 1];
if ((last + " " + x).Length > 40)
{
a.Add(x);
}
else
{
a[a.Count - 1] = (last + " " + x).Trim();
}
return a;
});

I get this out:


My school Name is stack over flow High
school.

Split string into strings by length?

>>> x = "qwertyui"
>>> chunks, chunk_size = len(x), len(x)//4
>>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
['qw', 'er', 'ty', 'ui']

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.

Split a string into smaller string by length

You are doing it right. Just return after str_split

    $str = $_POST['input']; //It will get the string from the input
$string = str_split($str, 4); // this is a array of strings with lenght 4
return $string;

The $string variable has the following structure:

Array
(
[0] => Hell
[1] => oFri
[2] => day
)

Split a long String into a specified size of smaller Strings

My recommendation would be to use a StringBuilder. Assuming you were given sendSMS from your question and you wanted to get str1 through str4, you might do this:

StringBuilder sb = new StringBuilder(sendSMS);
str1 = getStringFromSb(sb, 8);
str2 = getStringFromSb(sb, 4);
str3 = getStringFromSb(sb, 2);
str4 = getStringFromSb(sb, 2);

And the getStringFromSb method:

String getStringFromSb(StringBuilder sb, int stringLength)
{
String returnStr = sb.substring(0, stringLength);
sb.delete(0, stringLength);
return returnStr;
}

Split string into set of sub-strings with given length, delimited by separator

The hard part is handling the spaces, I think. This is what I came up with

  private string SplitString(string s, int maxLength)
{
string rest = s + " ";
List<string> parts = new List<string>();
while (rest != "")
{
var part = rest.Substring(0, Math.Min(maxLength, rest.Length));
var startOfNextString = Math.Min(maxLength, rest.Length);
var lastSpace = part.LastIndexOf(" ");
if (lastSpace != -1)
{
part = rest.Substring(0, lastSpace);
startOfNextString = lastSpace;
}
parts.Add(part);
rest = rest.Substring(startOfNextString).TrimStart(new Char[] {' '});
}

return String.Join(",", parts);
}

Then you can call it like this

  Console.WriteLine(SplitString("Smoking is one of the leading causes of statistics", 7));
Console.WriteLine(SplitString("Let this be a reminder to you all that this organization will not tolerate failure.", 30));

and the output is

Smoking,is one,of the,leading,causes,of,statist,ics
Let this be a reminder to you,all that this organization,will not tolerate failure.

pythonic way to split string into variable length chunks?

One way to do this, is with itertools.islice:

from itertools import islice

chunks = (1,2,6,1)
s = '0123456789'
assert len(s) >= sum(chunks)

it = iter(s)
result = [int(''.join(islice(it, i))) for i in chunks]
print(result)
# [0, 12, 345678, 9]

Split the string into different lengths chunks

>>> s = '25c319f75e3fbed5a9f0497750ea12992b30d565'
>>> n = [8, 4, 4, 4, 4, 12]
>>> print '-'.join([s[sum(n[:i]):sum(n[:i+1])] for i in range(len(n))])

Output

25c319f7-5e3f-bed5-a9f0-4977-50ea12992b30


Related Topics



Leave a reply



Submit