Я предлагаю использовать sprintf () в этом случае.
I обновил код, чтобы он отбрасывал все пробелы в начале, но 1. Таким образом, у вас будет знак - , затем пробел, а затем номер. Я оставил несколько комментариев в коде вместе с некоторыми комментариями printf () , чтобы помочь вам отладить код, если хотите.
#include <stdio.h>
int main()
{
char* num = " 1,54";
int c = 0;
if (strlen(num) > 0)
{
c = num[0]; // Safely storing the first character. Is it a whitespace?
}
else
{
printf("String is empty!\n");
return -1;
}
int wspace_count = 0; // number of whitespaces detected
while (c == 32) // ASCII 32 = whitespace
{
c = num[wspace_count];
if (c == 32)
wspace_count++;
}
//printf("whitespaces detected: %d\n", wspace_count);
//printf("total chars in num: %d\n", strlen(num));
int chars_to_copy = strlen(num) - wspace_count+1; // +1 becouse you want to leave 1 whitespace there, right?
//printf("chars_to_copy: %d\n", chars_to_copy);
int tmp_size = chars_to_copy + 1; // another +1 becouse you need to append '\0' at the end
char* tmp = malloc(tmp_size);
int pos = wspace_count - 1;
strncpy(tmp, &num[pos], chars_to_copy);
tmp[strlen(tmp)] = '\0'; // add '\0' at the end
//printf("tmp = \"%s\" \n", tmp);
char* result = (char*) malloc(strlen(tmp) + 3); // 1 byte for the - sign, 1 for the space after it, 1 for the '\0' at the end
sprintf(result, "- %s", tmp);
printf("%s\n", result);
return 0;
}
Выходы:
- 1,54