确定C中char数组的长度

时间:2014-02-20 17:41:49

标签: c arrays

我正在尝试确定char数组的长度。将char数组及其长度输入函数,并使用它执行一些操作。我试图确定它的大小。现在编写代码的方式由函数返回的长度大于预期。我来自java,所以如果我犯了一些看似简单的错误,我会道歉。我有以下代码:

/* 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;


}

1 个答案:

答案 0 :(得分:2)

如果您使用buf[j] = '\0',则字符串的长度为j

请记住,这不一定是最初分配的整个数组(buf)的大小。

在函数外部,您始终可以调用strlen(buf)来获取该长度,或者只是迭代buf直到遇到0个字符:

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'

请注意,上面的每个选项都会为您提供字符串的长度,不包括 0字符。