2015-11-06 57 views
0
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沿给定如"This is a message"maxSize则输出的功能应该是"This, is ,a me,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 , 

第二个逗号后面的字符为空,我找不到原因。有没有人有任何想法为什么?

+0

嗯,你上次'临时[msgSize] = '\ 0';'应该be' temp [msgSize + spacing] ='\ 0';',但我不确定是否证明结果正确。 – rodrigo

+0

@rodrigo间距是为了证明逗号,而msgSize意味着已经考虑到了这一点 –

+0

'msgSize'设置为'strlen(消息)'并且永不再修改。写入'temp'的最后一个有效字符是'temp [x + spacing]'并且在最后一次迭代'x == msgSize-1'中,所以'temp'的倒数第二个字符必须是'msgSize + spacing '(或'newSize'也许?),那就是NUL字符应该是的位置。 – rodrigo

回答

1

这段代码有两个问题。一个

temp[x] = ','; 

应该是:

temp[x + spacing] = ','; 

,因为这是如果条件是假的字符会。

两个,就是空我在评论中谈到:

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:你应该尝试使用调试器,它使得一些事情变得更容易...