Lesha
Lesha

Reputation: 182

Determining length of a char arrray in C

I am trying to determine the length of a char array. A char array and its length is fed into the function and some manipulation is performed with it. I am attempting to determine its size afterwards. The way the code is written now te length returned by the function is greater than expected. I am coming from java so I apologize if I'm making mistakes that seem simple. I have the following code:

/* The normalize procedure normalizes a character array of size len 
   according to the following rules:
     1) turn all upper case letters into lower case ones
     2) turn any white-space character into a space character and, 
        shrink any n>1 consecutive whitespace characters to exactly 1 whitespace

     When the procedure returns, the character array buf contains the newly 
     normalized string and the return value is the new length of the normalized string.

*/
int
normalize(unsigned char *buf,   /* The character array contains the string to be normalized*/
                    int len     /* the size of the original character array */)
{
    /* use a for loop to cycle through each character and the built in c functions to analyze it */
    int i = 0;
    int j = 0;
    int k = len;

    if(isspace(buf[0])){
        i++;
        k--;
    }
    if(isspace(buf[len-1])){
        i++;
        k--;
    }
    for(i;i < len;i++){
        if(islower(buf[i])) {
            buf[j]=buf[i];
            j++;
        }
        if(isupper(buf[i])) {
            buf[j]=tolower(buf[i]);
            j++;
        }
        if(isspace(buf[i]) && !isspace(buf[j-1])) {
            buf[j]=' ';
            j++;
        }
        if(isspace(buf[i]) && isspace(buf[i+1])){
            i++;
            k--;
        }
    }

    buf[j] = '\0';

   return k;


}

Upvotes: 0

Views: 327

Answers (1)

barak manos
barak manos

Reputation: 30146

If you use buf[j] = '\0', then the length of the string is j.

Keep in mind that this is not necessarily the size of the entire array (buf) initially allocated.

Outside the function, you can always call strlen(buf) in order to get that length, or simply iterate buf until you encounter a 0 character:

int i;
for (i=0; buf[i] != 0; i++) // you can use buf[i] != '\0', it's the same thing
{
}
// The length of the string pointed by 'buf' is 'i'

Please note that each of the options above gives you the length of the string excluding the 0 character.

Upvotes: 2

Related Questions