I have to do an assignment, where I have to remove the spaces from the end and the front of a text. (I don't know if there are always one in the front or in the end.)
So for example if my input is " Pls help me" then my output has to be "Pls help me" (no space in the front.) I cant use any more library that i'm using right now.
#include <stdio.h>
#include <string.h>
int *pIndexf; // pointer Index front (of the text)
int *pIndexe; // pointer Index end (of the text)
void trim(char source[], int size) {
// Checking the array from the front
for (int i = 0; i < strlen(source); i++) {
if (source[i] == ' ') {
pIndexf = &i;
break;
}
}
// Checking the array from behind
for (int i = strlen(source)-1; i > 0; i--) {
if (source[i] == ' ') {
pIndexe = &i;
break;
}
}
}
int main() {
char source[31] = {" Random text "}; // the array where i store the text i have to manipulate
char goal[31]; // this is where the trimmed text should be
trim(source, 31);
// Here i would add the source array's elements to the goal list without the spaces in a loop
}
It would be better if I could use the pointers to point back to the main
function instead of using them as a global variable.
I hope my problem is understandable.
ps.: I don't really understand pointers.
The assignment says that the function trim()
must take the source and destination arrays, so the function must do that.
The result of trimming is a string which may be as long as the source string or shorter, but never longer. Thus, the caller must always provide a destination array which is at least the size of the source array. With this usage requirement, there is no need to know the exact size of the destination array.
Also, there is no need to know the size of the source array since the C string will be zero-terminated.
Since standard library functions use the convention that the destination parameter comes before the source, the trim()
function may as well follow the same convention. For the same reason, a pointer to the resulting string may be returned so the function can be used in composed expressions.
For the implementation itself, a strategy could be:
Following this, an implementation is:
#include <string.h>
char *trim(char *dest, const char *src)
{
size_t end = strlen(src); // Step 1
while(end > 0 && src[end-1] == ' ') end--; // Step 2
size_t begin = 0;
while(begin < end && src[begin] == ' ') begin++; // Step 3
size_t dest_index = 0;
while(begin < end) dest[dest_index++] = src[begin++]; // Step 4
dest[dest_index] = 0; // Step 5
return dest;
}
Notice that end
points one past the last non-space character, not at the last non-space character itself. This allows for correct handling of the corner cases (empty string or a string having all spaces) where end
will be zero.
Example of usage:
const char src[] = " Pls help me";
char dest[sizeof(src)];
trim(dest, src);