Tuesday, May 29, 2007

Math.Ceiling Error

Reviewing a string splitting function that was throwing an index out of range error proved to be a *problem* with Math.Ceiling.
The said function simply takes any sized string and the length that the caller wants each line to equal and returns a new string array with each row holding a line of the specified length.

---------------------------------------------------------------
public static string[] SplitStringToLines(string s, int lineLength)
{
  int sLength = (s == null ? 0 : s.Length);
  int totLines = Convert.ToInt32(Math.Ceiling(sLength/(lineLength <= 0 ? sLength : lineLength)));
  string[] lines = new string[totLines];

  int line = 0;
  int length = 0;
  int startIndex = 0;
  while (startIndex < sLength)
  {
    length = Math.Min(sLength-startIndex, lineLength);
    lines[line] = s.Substring(startIndex, length);
    startIndex += length;
    line += 1;
  }
  return lines;
}
---------------------------------------------------------------

The cure came when I casted the variables being fed to Math.Ceiling, which makes sense when viewing the overloaded details provided by microsoft.
Changing the Math.Ceiling line to:
Convert.ToInt32(Math.Ceiling((double)sLength/(lineLength <= 0 ? (double)sLength : (double)lineLength)));

remedied the index error.

No comments: