Splits a string effeciently using vectors

/**
* Splits the Long string so that it can be wrapped on the screen
* @param strText Text to be wrapped
* @author Gudipati Pradeep - Wipro
*/
public static String[] splitString(String strText, Font font, int screenWidth) {
String strTemp = "";
int nLastBreakPos = 0;
int nLastBreakInString = 0;
int nPosInString = 0;
int nCharacter = 0;
int nStringWdInPixel = 0;
int width = screenWidth - 5 * 3;
Vector splitString = new Vector();

/* Before adding the nCharacter, check that the length of the string isn't already at the max */
for (int i = 0; i < strText.length(); i++) {
nCharacter = strText.charAt(i);
nPosInString++;
strTemp += strText.charAt(i);
nStringWdInPixel += font.charWidth(strText.charAt(i));

if ((nCharacter == ' ') || (nCharacter == '.') || (nCharacter == '!') || (nCharacter == '?') || (nCharacter == ',') || (nCharacter == '-') || (nCharacter == '=')) {
nLastBreakPos = i;
nLastBreakInString = nPosInString;
}

if ((nStringWdInPixel >= width) || (i >= strText.length() - 1)) {

/* This case would take care of strings that are too long to fit in one line. */
if (nLastBreakInString <= 0) {

/* Force a break in the string and move the pointer back by 1 */
if (nStringWdInPixel >= width) {

/*
* String was too long so we force an un-natural break mid text
* we go back one nCharacter prior to clipping the edge
*/
if (strTemp.length() > 0) {
splitString.addElement(strTemp.substring(0, (strTemp.length() - 1)));
} else {
splitString.addElement("");
}

i = i - 1;
strTemp = "";
nPosInString = 0;
nLastBreakInString = 0;
nStringWdInPixel = 0;
} /* This case occurs when the last word is very long and does not break on its own. */ else {
splitString.addElement(strTemp.substring(0, strTemp.length()));
strTemp = "";
nPosInString = 0;
nLastBreakInString = 0;
nStringWdInPixel = 0;

break;
}
} /* This case would break natural lines. */ else {
if (nStringWdInPixel >= width) {
splitString.addElement(strTemp.substring(0, nLastBreakInString));
i = nLastBreakPos;
strTemp = "";
nPosInString = 0;
nLastBreakInString = 0;
} else {
splitString.addElement(strTemp.substring(0, strTemp.length()));
strTemp = "";
nPosInString = 0;
nLastBreakInString = 0;
break;
}
}
}
}


int nSize = splitString.size();
for (int t_int = 0; t_int < nSize - 1; t_int++) {
String temp = (String) splitString.elementAt(t_int);
if (temp.equals("")) {
splitString.removeElementAt(t_int);
}
}
nSize = splitString.size();
String[] m_arrstrSplitText = new String[nSize];
for (int t_int = 0; t_int < nSize; t_int++) {
String temp = (String) splitString.elementAt(t_int);
if (!temp.equals("")) {
m_arrstrSplitText[t_int] = temp;
}
}

splitString.removeAllElements();
splitString = null;
return m_arrstrSplitText;
}

Comments

Popular posts from this blog

How to create Component-preload.js files for Fiori Applications

How to create a new user in Open DS LDAP server for Sybase Unwired Platform

Building Cost Effective Enterprise Mobile Applications