我试图实现一个函数来修改字符串:
代码如下:
test.h文件:
#ifndef header_file
#define header_file
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char * findWord(char *, char *);
#endif
测试.c文件:
#include"test.h"
char * findWord(char *array, char *action)
{
char testchar;
int count=0, i=0, j, start = 0, end, wordLength = 0, charCount =0, k=0;
char *temp = malloc(sizeof(char)*400);
char *word = malloc(sizeof(char)*30);
char *replaceString = malloc(sizeof(char)*80);
if(strcmp(action,"replace") == 0)
{
while((testchar = array[i]) != '\0')
{
if(testchar == ',')
{
start = i+1;
i++;
continue;
}
else if(testchar == ':')
{
end = i;
word[charCount] = '\0';
charCount = 0;
printf("Start is: %d \n", start);
for(j=0; j< strlen(array); j++)
{
if(j == start)
{
sprintf(replaceString, "%s%s%s", "replace_",word,"_ii");
printf("Replace String for word %s is %s.\n",word,replaceString);
strcat(temp,replaceString);
j = (j-1)+(strlen(word));
k= strlen(replaceString);
printf("The value of J is %d for word %s.\n",j,word);
}
else
{
temp[k++] = array[j];
}
}
temp[k] = '\0';
k=0;
printf(" Words %s is replaced. The new string is:\n", word);
printf("%s\n",temp);
memset(word,'0',30);
memset(temp,'0',400);
memset(replaceString,'0',80);
i++;
continue;
}
if(testchar != 'Y')
{
word[charCount] = testchar;
charCount++;
}
i++;
}
}
else if(strcmp(action,"MISSING") == 0)
{
}
else if(strcmp(action,"EMPTY") == 0)
{
}
else
printf("Something went wrong.\n");
free(temp);
free(word);
free(replaceString);
}
主.c文件:
#include"test.h"
int main()
{
char sc[] = "cn:Y,x509UniqueIdentifier:Y,pseudonym:Y,name:Y,l:Y,street:Y,state:Y,postalAddress:Y,postalCode:Y,telephoneNumber:Y,emailAddress:Y";
findWord(sc, "replace");
return 0;
}
预期产出为:
Replace String for word cn is replace_cn_ii.
replace_cn_ii:Y,x509UniqueIdentifier:Y,pseudonym:Y,name:Y,l:Y,street:Y,state:Y,postalAddress:Y,postalCode:Y,telephoneNumber:Y,emailAddress:Y
是的。
是的。
是的。
10输出。
但由于
strlen()
的意外行为,它给出了垃圾值。strcat()
功能后的单词值自动更改。我哪里做错了?
告诉我这个问题以及如何解决它。
谢谢!
最佳答案
您正在对strcat()
调用temp
,但temp
不包含有效字符串。这给出了未定义的行为。
必须首先确保temp
有效,即使其成为空字符串:
*temp = '\0';
当然,您还必须确保分配成功。
关于c - strlen函数的意外输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30706510/