[英]Split string into two strings by delimiter
我尝试使用此代码通过定界符将字符串分成两个字符串
int indexOf(char *msg, char c) {
int i;
for (i = 0; msg[i] != '\0'; i++) {
if (msg[i] == c)
return i;
}
return -1;
}
char *substring(char *msg, int startIndex, int endIndex) {
int length = endIndex - startIndex;
char *input = (char *)malloc(length * sizeof(char) + 1);
int i;
for (i = startIndex; i != endIndex; i++) {
input[i - startIndex] = msg[i];
}
input[endIndex] = '\0';
return input;
}
我main
有:
index = indexOf(msg, ':');
first = substring(line, 0, index - 1);
second = substring(line, index + 2, strlen(line));
当我用valgrind测试它时,此代码会产生正确的输出。 在第二个变量中分配的子字符串产生一个错误。
此功能的问题在哪里? 还有另一种方法可以将字符串分成两个字符串吗?
char *msg = readMessage(stdin);
index = indexOf(msg, '\n');
char *line, *first, *second;
line = substring(msg, 0, index);
结束valgrind Address 0x5203a52 is 5 bytes after a block of size 13 alloc'd
编辑 :有另一个错误
index = indexOf(line, ':');
现在,valgrind错误出现在input[endIndex] = '\\0';
行input[endIndex] = '\\0';
子字符串中input[endIndex] = '\\0';
:
Invalid write of size 1
编辑 :我的代码有两个错误的解决方案
在主要
index = indexOf(msg, ':');
应该
index = indexOf(line, ':');
并在子串中
input[endIndex] = '\0';
应该
input[length] = '\0';
谢谢大家
index = indexOf(msg, ':');
^^^
line ?
这里
second = substring(line, index+2, strlen(line));
您假设该行比index + 2长。 您应该检查一下以避免在malloc
调用中为零。 换句话说-如果定界符是最后一个字符,则会遇到问题。
您应该添加对malloc
返回的值的检查
if (!input)
{
// Print error message
exit(1);
}
顺便说一句-看一下strdup
和memcpy
或strncpy
您的代码中存在一些问题:
input[endIndex] = '\\0';
使用错误的索引。 它应该input[length] = '\\0';
在main()
,您不应对indexOf
的返回值进行隐式假设。 张贴的代码调用未定义的行为,如果:
在没有找到line
:
这是一个更安全的版本:
int index = indexOf(line, ':');
if (index >= 0) {
// found the `:` separator
char *first = substring(line, 0, index);
if (line[index + 1] == ' ') {
index++; // skip the space after the :
}
char *second = substring(line, index + 1, strlen(line));
...
}
您可以使用strcspn()
代替indexOf
通过更少的测试提取零件:
char *msg = readMessage(stdin);
size_t index = strcspn(msg, "\n");
char *line = substring(msg, 0, index);
...
strcspn()
返回其参数字符串中最多包含但不包含和的字符数。 如果存在字符,则返回与indexOf()
相同的值(除了size_t
类型而不是int
),并且如果不存在则返回字符串的长度,这正是您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.