Friday, January 25, 2013

c# fixed position in strings

I had to update how the characters in a string were positioned.  Previously the fields in the string were variable length without any delimiters.

Like this:  LastName,FirstNameMrnAccountNumberRegDate

The requirements had changed. There was a need to have each field start in a know position and space fill any unused positions in that field.

Like this:  LastName, FirstName          MRN    AccountNumber    RegDate


I seem to remember in COBOL there was some kind of FILLER command.  Something along the lines of
FILLER(30) that would add 30 spaces.

Back to C#  I went about this using char arrays.  Each field would have a char array, the number of elements in each char array would be equal to the field size.  A method gets called to space fill the arrays. Next the string data is loaded element by element into the char arrays. This is easy code since a c# string is an array of characters.  The last step is to combine the char arrays into one string.  I used the string(char) constructor and the string.format methods to complete this.


        string LastName = "Clause";
        string FirstName = "Santa";
        string MRN = "0000007xx";
        string PatComCode = "378";
        DateTime RegDate = DateTime.Now;       
       
        string noteCode2 = string.Empty;
         
        string name = string.Format("{0}, {1}", LastName, FirstName);
 
        char[] nameArray = new char[29];
        spaceFillArray(ref nameArray);
 
        char[] mrnArray = new char[7];
        spaceFillArray(ref mrnArray);
 
        char[] acctArray = new char[9];
        spaceFillArray(ref acctArray);
 
        char[] regDtArray = new char[10];
        spaceFillArray(ref regDtArray);
 
        stringToArray(ref nameArray,name);
        stringToArray(ref mrnArray,MRN);
        stringToArray(ref acctArray,PatComCode);
        stringToArray(ref regDtArray,RegDate.ToString("MM/dd/yyyy"));        
 
 
        noteCode2 =  buidPatInfoString(nameArray,mrnArray,acctArray,regDtArray);



private void spaceFillArray(ref char[] info)
    {
        for (int i = 0; i < info.Length; i++)
        {
            info[i] = ' ';
        }
    }
 
 
    private void stringToArray(ref char[] info, string inString)
    {
        for(int i = 0; i < inString.Length; i++)
        {
            if (i == info.Length)
                break;
            
            info[i] = inString[i];
        }
    }
    
    
    private string buidPatInfoString(char[] name, char[] mrn, char[] acct, char[] regDt)
    {
        string ret = string.Empty;
 
        string partA = new string(name);
        string partB = new string(mrn);
        string partC = new string(acct);
        string partD = new string(regDt);
 
        ret = string.Format("{0}{1}{2}{3}",partA,partB,partC,partD);
 
        return ret; 
    }       

No comments: