add space to every word's end in a string in C
Posted
by
hlx98007
on Stack Overflow
See other posts from Stack Overflow
or by hlx98007
Published on 2013-11-03T02:40:58Z
Indexed on
2013/11/03
3:53 UTC
Read the original article
Hit count: 181
Here I have a string:
*line = "123 567 890 ";
with 2 spaces at the end. I wish to add those 2 spaces to 3's end and 7's end to make it like this:
"123 567 890"
I was trying to achieve the following steps:
- parse the string into words by words list (array of strings). From upstream function I will get values of variables word_count, *line and remain.
- concatenate them with a space at the end.
- add space distributively, with left to right priority, so when a fair division cannot be done, the second to last word's end will have (no. of spaces) spaces, the previous ones will get (spaces + 1) spaces.
- concatenate everything together to make it a new *line.
Here is a part of my faulty code:
int add_space(char *line, int remain, int word_count)
{
if (remain == 0.0)
return 0; // Don't need to operate.
int ret;
char arr[word_count][line_width];
memset(arr, 0, word_count * line_width * sizeof(char));
char *blank = calloc(line_width, sizeof(char));
if (blank == NULL)
{
fprintf(stderr, "calloc for arr error!\n");
return -1;
}
for (int i = 0; i < word_count; i++)
{
ret = sscanf(line, "%s", arr[i]); // gdb shows somehow it won't read in.
if (ret != 1)
{
fprintf(stderr, "Error occured!\n");
return -1;
}
arr[i] = strcat(arr[i], " "); // won't compile.
}
size_t spaces = remain / (word_count * 1.0);
memset(blank, ' ', spaces + 1);
for (int i = 0; i < word_count - 1; i++)
{
arr[0] = strcat(arr[i], blank); // won't compile.
}
memset(blank, ' ', spaces);
arr[word_count-1] = strcat(arr[word_count-1], blank);
for (int i = 1; i < word_count; i++)
{
arr[0] = strcat(arr[0], arr[i]);
}
free(blank);
return 0;
}
It is not working, could you help me find the parts that do not work and fix them please? Thank you guys.
© Stack Overflow or respective owner