- Home /
String split by length
i have a string with 75 characters , i want to take 25 characters to another string how can i do that?
Answer by Statement · Mar 25, 2011 at 01:47 PM
Use String.SubString.
var bar = foo.Substring(0, 25);
bar will contain the first 25 characters of foo.
var bar = foo.Substring(index, length);
bar will contain length characters from foo, starting from index.
If you want to create a function that chops a string by length and return an array of those strings, here's one in C#:
public static string[] Chop(string value, int length)
{
int strLength = value.Length;
int strCount = (strLength + length - 1) / length;
string[] result = new string[strCount];
for (int i = 0; i < strCount; ++i)
{
result[i] = value.Substring(i * length, Mathf.Min(length, strLength));
strLength -= length;
}
return result;
}
Example usage:
string bar = "this is an incredible long string that will be chopped down"; string[] foo = Chop(bar, 10);
foreach(string f in foo) Debug.Log(string.Format("[{0}]", f));
If you want you can make it an extension to string.
public static class StringChop
{
public static string[] Chop(this string value, int length)
{
int strLength = value.Length;
int strCount = (strLength + length - 1) / length;
string[] result = new string[strCount];
for (int i = 0; i < strCount; ++i)
{
result[i] = value.Substring(i * length, Mathf.Min(length, strLength));
strLength -= length;
}
return result;
}
}
Then you can use it like this:
string bar = "this is an incredible long string that will be chopped down"; string[] foo = bar.Chop(10);
foreach(string f in foo) Debug.Log(string.Format("[{0}]", f));
Your answer
Follow this Question
Related Questions
StringSplitOptions.RemoveEmptyEntries - Unknown identifier 2 Answers
issues splitting strings 1 Answer
Extract number from string? 3 Answers
Split a string every 'n' characters? 5 Answers
How to split a string into array? 2 Answers