BuildFixedWidth sample
The BuildFixedWidth sample accepts an array of Strings and an array of Widths to generate a fixed Width format String. If the token has newline characters (\n) or CRLF characters (\r) and is being considered by the width for the token, the token is embedded in double quotation marks.
package com.ibm.ccd.api.samplecode.parser;
import com.ibm.ccd.api.samplecode.StringUtils;
public class BuildFixedWidth
{
public static String build(String[] aValues, int[] aWidths)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < aValues.length; i++)
{
String sValue = aValues[i];
int nWidth = aWidths[i];
String sPaddedValue = padStringToRight(sValue, nWidth, ' ');
if (sPaddedValue.length() > nWidth)
{
sPaddedValue = sPaddedValue.substring(0, nWidth);
}
if ((sPaddedValue.indexOf("\n") >= 0) || (sPaddedValue.indexOf("\r") >= 0))
{
sb.append("\"");
sb.append(StringUtils.replaceString(sPaddedValue, "\"", "\"\""));
sb.append("\"");
}
else
{
sb.append(sPaddedValue);
}
}
return sb.toString();
}
private static String padStringToRight(String sArg, int len, char padChar)
{
StringBuffer buf = new StringBuffer(len);
int arg_len = sArg.length();
int needed_len = len - arg_len;
buf.append(sArg);
if (arg_len < len)
{
for (int i = 0; i < needed_len; ++i)
{
buf.append(padChar);
}
}
return buf.toString();
}
public static void main(String args[])
{
String [] sValues = {"a", "bb", "ccc" , "dddd"};
int [] iWidth = {1, 1, 3, 4};
System.out.println(build(sValues, iWidth));
}
}