Splitting String only on a "space". Using my method --- FIXED

Good afternoon all,

I am trying to create a RPG style text, and I wish to split up a single string given in and have it split into an array based on how many characters are allowed in each array index. Here is the code I have been working on.

float remainder = newText.Length % splitIndex;
_textBlocks = new string[(int)(Mathf.Floor(newText.Length / (float)splitIndex)) + ((remainder==0) ? 0 : 1)];
for(int x = 0; x < _textBlocks.Length; x++)
{
	_textBlocks[x] = newText.Substring(x*splitIndex, (int)((x==_textBlocks.Length-1) ? remainder : splitIndex));
}

The above code does what I wish: The Issue IS It splits in the middle of words depending on the string passed in.

I was thinking of while looping backward until it hits an empty string then add that array to the _textBlocks. However the methods I am trying yield no good result, or gives more issues than it solves.

OTHER THEORY:

Split the entire string via. string.split(" "[0]) then count each array length, add it to clump value, if that value exceeds splitIndex, then add string.split values that include what we just looked at… Confusing, a bit. Hopfully someone can help me make sense of this.

It would be helpful if you post an input-string and the result that you want to have.
The code above splits the text with substring. There is no code to deal with words or spaces. At least i can’t see one.

If you want to display text with a certain width (say 20 characters):

 - Split the text after each word (with split, as you said)
 - take the first word as actual string
 - A: take the next word
 - if actual string + space + next word is longer than splitIndex put actual string in array, the next word is the new first word
- if not, bind the next word to the actual string
 - redo from A: until no more words

FIXED, I ended up looping through the arrays after they were built and fixing them accordingly.

float remainder = newText.Length % splitIndex;
_textBlocks = new string[(int)(Mathf.Floor(newText.Length / (float)splitIndex)) + ((remainder==0) ? 0 : 1)];

for(int x = 0; x < _textBlocks.Length; x++)
{
	_textBlocks[x] = newText.Substring(x*splitIndex, (int)((x==_textBlocks.Length-1) ? ((remainder==0) ? splitIndex : remainder) : splitIndex));
}

for(int x = 0; x < _textBlocks.Length; x++)
{
	while(_textBlocks[x].Substring(_textBlocks[x].Length - 1) != " ")
	{
		if(x+1 != _textBlocks.Length)
		{
			_textBlocks[x+1] = _textBlocks[x+1].Insert(0, _textBlocks[x].Substring(_textBlocks[x].Length - 1));
			_textBlocks[x] = _textBlocks[x].Remove(_textBlocks[x].Length - 1);
		}
		else
			break;
	}
}

YAY :smiley: Finally I can move on!