我正在使用一个小函数,该函数应该打破子字符串中的字符串,以确保不会剪切任何单词。
让我们来看看这个用例:
“出了点问题,我不知道出了什么问题”
总字数:63;
每行的最大字符长度为 15,我会得到这个 substr “something is go”
如您所见,当我想获得整个单词时,它正在削减单词。
line[1]: something is //break the string on the last space bellow the max chars length;
line[2]: 出错 .... // 包括第二行开头第一行缺失的字符
line[3]: .... //依此类推,直到所有字符都被循环。
我想出了这个让我发疯的解决方案。
function splitString(obj:Object):Array{
if (obj.hasOwnProperty("d_string"))
{
var texto:String = obj.d_string;
var textoStr:Array = texto.split("");
var textoLen:Number = texto.length;
trace("textoLen " + textoLen);
var maxCharPerLine:Number;
if (obj.hasOwnProperty("d_limit")){
maxCharPerLine = obj.d_limit;
trace("maxCharPerLine" + maxCharPerLine);
}else{
maxCharPerLine = 20;
}
var textLine:Array = [];
var currentLine:Number = 1;
var currentIndex:Number = 0;
var cachedCharsForLine:Array = []; //all characters between the range
var lastCachedCharsForLine:Array = []; //mirror of all characters stoping at the last space found
var missingChars:Array = [];
var canCleanData:Boolean = false;
/*START LOOPING OVER THE STRING*/
for (var i:Number = 0; i< textoLen; i++)
{
//<block1>
if ( currentIndex == maxCharPerLine || i == textoLen -1 ){
canCleanData = true;
}
//<block2> 22
if ( currentIndex <= maxCharPerLine ){
cachedCharsForLine.push(textoStr[i]);
//trace(cachedCharsForLine);
}
trace(textoStr[i]);
trace(textoStr[i] == " ");
/*is the characters a space?*/
if (textoStr[i] == " ") {
/*1. even after the condition above returns false*/
lastCachedCharsForLine = [];
lastCachedCharsForLine = cachedCharsForLine;
}
/*as you can see from the output this value is being updated every iteration after the first space get found
when it was suppose to be updated only if the a char of type <space> get found"
*/
trace("-----------------" + lastCachedCharsForLine)
//<block4>
if( currentIndex == maxCharPerLine || i == textoLen -1 ){
if (textoStr[i]==" " || textoStr[i+1]==" "){
trace("\n A");
//trace("@@@ " + lastCachedCharsForLine);
textLine[currentLine] = lastCachedCharsForLine;
trace("//" + textLine[currentLine]);
}
else{
trace("\n B");
//trace("@@@ " + lastCachedCharsForLine);
textLine[currentLine] = lastCachedCharsForLine;
trace("//" + textLine[currentLine]);
}
currentIndex = 0;
currentLine ++;
}
//<block5>
if (currentLine > 1 && canCleanData){
trace("DATA CLEANED");
canCleanData = false;
cachedCharsForLine = [];
lastCachedCharsForLine = [];
}
currentIndex ++;
}
return textLine;
}else{
return textLine[0] = false;
}
}
var texto:String = "Theres something going wrong and it's driving me crazy.";
var output:Array = []
output = splitString({"d_string":texto,"d_limit":15});
for (var i:Number = 0; i<output.length; i++){
trace(output[i] + "\n\n");
}
从这条跟踪线可以看出,lastCachedCharsForLine 的变量正在更新。
trace("-----------------" + lastCachedCharsForLine)
即使下面的条件返回 false
if (textoStr[i] == " ") {
/*1. even after the condition above returns false*/
lastCachedCharsForLine = [];
lastCachedCharsForLine = cachedCharsForLine;
}