lundi 2 mars 2015

Cutting a string at specified lengths

I've got an array that holds strings, and I wanted to know how I could take a string and cut a part off at a specified pixel length and add it into the array.


For Example,



string[] string1 = { "Hello World" };


I'm using XNA so I can get the pixel length by using,



FontName.MeasureString(string1[0]).Length()


So for example, if the above code returns 100 pixels long how can I cut the string at 70 pixels long and add it back to the array to get this:



string1 = { "Hello Wo", "rld" } // Hello Wo(100px), rld(30px)


I've look at using StringBuilder but it measures strings in character length. If there are no possible ways to accomplish this, would there be a way to instead find out how many characters are in between the start of the string and the pixel point of where I want the string to cut off at, so then I would be able to use StringBuilder.


Edit:


So I tried looping through the array and then looping through each character in the array and adding it to a list, it somewhat works but I'm having trouble getting it to continue after it adds it back to the array.



string[] stringArray = { "Hello World" };
List<Char> charList = new List<Char>();
List<Char> charList2 = new List<Char>();
List<String> stringList = new List<String>();


for (int i = 0; i < stringArray.Length; i++)
{
if ((int)consolas.MeasureString(stringArray[i]).Length() > 30)
{
for (int c = 0; c < stringArray[i].Length; c++)
{
if (consolas.MeasureString(string.Join("", charList)).Length() < 30)
{
charList.Add(stringArray[i][c]);
}
else
{
charList2.Add(stringArray[i][c]);
}
}
}
}

stringList.Add(string.Join("", charList));
stringList.Add(string.Join("", charList2));
stringArray = stringList.ToArray();
charList.Clear();
charList2.Clear();
stringList.Clear();


The above code returns me with



stringArray = { "He", "llo World" };


which is what I wanted but I want it to continue to do this



stringArray = { "He", "ll", "o World" };


and keep continuing to split the strings when they pass the 30px. I've thought about it and I can't seem to see why it isn't splitting further.


Aucun commentaire:

Enregistrer un commentaire