char *placeDelimiter(char message[], int maxSize) {
int msgSize = strlen(message); //length of message
int delSize = (msgSize/maxSize);//how many delimiters are needed
int remSize = msgSize%maxSize; //remainder characters
int newSize = msgSize+delSize; //new size of message
if (remSize==0) delSize--; //if there are no remainders remove , from end
char *temp = (char *)malloc(newSize+1);
int delPos = 0;
int spacing = 0;
for (int x=0;x<msgSize;x++) {
if (delPos==maxSize) {
temp[x] = ',';
delPos=0;spacing++;
} else {delPos++;}
temp[x+spacing] = message[x];
printf("Char: %c DelPos: %d Spacing: %d\n", temp[x], delPos, spacing);
}
temp[msgSize] = '\0';
return temp;
}
上面的函数每隔设定数量的字符放置一个分隔符 (maxSize
)
当函数在输入中给出,例如 “这是一条消息”
以及 4
表示 maxSize
时,输出应为 “这是,一个我,ssag,e”
。但是,存在一个问题,即在循环期间给出空字符,该字符显然充当字符数组的末尾
我在循环中添加了 printf 以在过程中提供更多信息,这是给出的输出:
Char: T DelPos: 1 Spacing: 0
Char: h DelPos: 2 Spacing: 0
Char: i DelPos: 3 Spacing: 0
Char: s DelPos: 4 Spacing: 0
Char: , DelPos: 0 Spacing: 1
Char: DelPos: 1 Spacing: 1
Char: i DelPos: 2 Spacing: 1
Char: s DelPos: 3 Spacing: 1
Char: DelPos: 4 Spacing: 1
Char: , DelPos: 0 Spacing: 2
Char: DelPos: 1 Spacing: 2
Char: DelPos: 2 Spacing: 2
Char: m DelPos: 3 Spacing: 2
Char: e DelPos: 4 Spacing: 2
Char: , DelPos: 0 Spacing: 3
Char: s DelPos: 1 Spacing: 3
Char: DelPos: 2 Spacing: 3
This, is ,
第二个逗号后面的字符为空,我找不到原因。有谁知道为什么吗?
最佳答案
这段代码有两个问题。一个
temp[x] = ',';
应该是:
temp[x + spacing] = ',';
因为如果条件为假,这就是角色所在的位置。
第二,是我在评论中谈到的 NUL:
temp[msgSize] = '\0';
应该是:
temp[msgSize + spacing] = '\0';
IMO,如果使用两个索引变量而不是偏移量,会更容易理解。像这样的东西:
for (x = 0, y = 0; x < msgSize; ++x, ++y)
{
if (...)
temp[y++] = ',';
temp[y] = message[x];
}
temp[y] = '\0';
PS:您应该尝试使用调试器,它使某些事情变得更容易......
关于Char 数组意外的空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569534/