c - 规范化 char 数组并删除多余的字符(截断)

标签 c arrays normalization truncate

我有以下用于规范化 char 数组的代码。在该过程结束时,规范化文件最后会留下一些旧的输出。这是为了 ij 之前到达数组的末尾。这是有道理的,但如何删除多余的字符?我来自 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.

     hint: you may want to use C library function isupper, isspace, tolower
     do "man isupper"
*/
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 funstions 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--;
        }
    }

   return k;

}

这是一些示例输出:

halb mwqcnfuokuqhuhy ja mdqu nzskzkdkywqsfbs zwb lyvli HALB MwQcnfuOKuQhuhy Ja mDQU nZSkZkDkYWqsfBS ZWb lyVLi

如您所见,结尾部分在重复。新的规范化数据和旧的剩余未规范化数据都出现在结果中。我该如何解决这个问题?

最佳答案

添加一个空终止符

k[newLength]='\0';
return k;

关于c - 规范化 char 数组并删除多余的字符(截断),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21867621/

相关文章:

javascript - 使用 Javascript 将数据存储在大型数组中时的性能问题

c++ - 自动更改 C++ 名称约定

sql - 表的规范化

ios - 如何在 Swift 中按数字和字母顺序对数组进行排序

php - 按数值排列的 Glob 数组

database-design - 我如何标准化这个数据库设计?

c - 删除和 DFS 功能无法正常工作

c - exp 函数在 Mac 和 Linux 上的结果略有不同

c - 结构与 union : structure has no member named

python /赛通 : Using SciPy with Cython