【发布时间】:2020-12-18 09:54:23
【问题描述】:
第一次在这里提问: 好吧,我需要使用原始字符串 并从字符串中删除空格和数字 我需要使用确切的内存量。
由于某种原因,字符串开头很好 但随后它会打印垃圾值:
原始字符串:"abcd2 34fty 78 jurt#"
需要做什么:abcdftyjurt#
我的代码:
#define _CRT_SECURE_NO_WARNINGS
#include <malloc.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
/* Function declarations */
/*-------------------------------------------------------------*/
void Ex1();
char* clearDigitsAndSpaces(char*);
/*-------------------------------------------------------------*/
void Ex2();
/*-------------------------------------------------------------*/
void Ex3();
/*-------------------------------------------------------------*/
/* Declarations of other functions */
int main() {
int select = 0, i, all_Ex_in_loop = 0;
printf("Run menu once or cyclically?\n(Once - enter 0, cyclically - enter other number) ");
if (scanf("%d", &all_Ex_in_loop) == 1)
do {
for (i = 1; i <= 3; i++)
printf("Ex%d--->%d\n", i, i);
printf("EXIT-->0\n");
do {
select = 0;
printf("please select 0-3 : ");
scanf("%d", &select);
} while ((select < 0) || (select > 3));
switch (select) {
case 1: Ex1(); break;
case 2: Ex2(); break;
case 3: Ex3(); break;
}
} while (all_Ex_in_loop && select);
return 0;
}
/* Function definitions */
void Ex1() {
char input[] = "abcd2 34fty 78 jurt#";
char *temp = NULL;
temp = clearDigitsAndSpaces(input);
printf("%s\n ", temp);
free(temp);
}
char *clearDigitsAndSpaces(char *old_string) {
char *new_string;
int count = 0;
int i = 0;
int j = 0;
int size = strlen(old_string);
new_string = (char *)malloc(size * sizeof(char));
assert(new_string); /*Memory allocation check*/
while (old_string[i]) {
if (old_string[i] != ' ' && (old_string[i] > '9' || old_string[i] < '0')) {
new_string[j++] = old_string[i];
} else {
//size -= 1;
new_string = (char *)realloc(new_string, size - 1);
}
i++;
}
assert(new_string);
//printf("%s", new_string);
return new_string;
}
void Ex2() {
}
void Ex3() {
}
【问题讨论】:
-
这是 C 还是 C++?选择一个。
-
No-code-look 评论:您是否 NULL 终止了您的字符串?我认为 OP 打算将其标记为 C.
-
只需在您的 std::string 上使用
shrink_to_fit。 -
正如@gsamaras 所暗示的,您需要:
int size = strlen(old_string) + 1;以容纳nul终止符。 (strlen返回值不包括它。) -
不要忘记计算 NUL 终止字符,即
strlen(...)+1并且不要忘记在末尾复制它...