我正在尝试编写一个从字符串中删除空格的函数,但输出根本不合理。我需要帮助家人!
代码:
char* deleteSpace(char *String, int n) {
int i;
char* withoutSpaces;
withoutSpaces = calloc(n, sizeof (char));
for (i = 0; i < n - 1; i++) {
if (String[i] == ' ')
withoutSpaces[i] = String[++i];
else
withoutSpaces[i] = String[i];
}
return withoutSpaces;
}
最佳答案
您需要为源字符串建立“读取”索引,为目标建立“写入”索引。
此外,为了获得更好的可调试性和可读性,请将索引增量 ++i
放在单独的行上。哦 - 看来您将 i
增加了两次。一次通过循环隐式调用,然后再次使用 ++i
。
还不清楚 n 是否表示带或不带空终止符的字符串的长度。因此,让我们让函数通过 strlen 来解决这个问题。
不要忘记以 null 终止输出字符串。
还有其他几个错误。这是改进的版本:
char* deleteSpace(const char *String) {
int j = 0;
const char* ptr = String;
size_t n = 0;
size_t spaces = 0;
char* withoutSpaces = NULL;
// count how many characters we expect to copy over
while (*ptr) {
n += (*ptr == ' ') ? 0 : 1;
ptr++;
}
withoutSpaces = (char*)malloc(n+1); // +1 for null char
for (i = 0; i < n; i++) {
if (String[i] != ' ') {
withoutSpaces[j] = String[i];
j++;
}
}
withoutSpaces[j] = '\0';
return withoutSpaces;
}
此外,如果您只想将字符串压缩到位而不分配新字符串。
void deleteSpace(char *String) {
char* ptrWrite = String;
while (*String) {
if (*String != ' ') {
*ptrWrite = *String;
ptrWrite++;
}
String++;
}
*ptrWrite = '\0';
}
关于c - 程序返回一些奇怪且不完整的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550699/