2012年1月18日 星期三

Character alignment

To put a string at a certain position, I wrote a simple java method.


Ex: firstSegLength = 20 , a = stringA, b = stringB
      Output =stringA             stringB 


There are 13 space character between stringA and stringB.


public String string_alignment(int SegLength,String a,String b)
  {
String output = null;
int len = a.length();

//Error check
if((SegLength < 1) || (a == null) || (b == null))
return null;
if(a.length() > (len - 1))
{
//should not be happened, case handle
}
int totallen = SegLength + b.length();
int sepLen = SegLength - len;
StringBuilder workstr = new StringBuilder();
//append first string
workstr.append(a);


//create space string
char seprator[] = new char[sepLen];
for(int i = 0;i < sepLen; i++)
{
seprator[i] = ' ';
}
        //append the second string
workstr.append(seprator);
workstr.append(b);
output = workstr.toString(); 
return output;
  }

沒有留言:

張貼留言