void trimArray(const char *toTrim, char *newArray)

This is my code but it is wrong
// The function trimArray() is given a pointer to a character array that// is NULL terminated called toTrim. This function is to remove any space characters// that exist between the last non-space character and the NULL character in the toTrim array.// Example, the following character string "This text " should be trimmed// (or altered) to be "This text". The trimmed array is put in the array// pointed to by the newArray pointer. Assume that the array pointed to by newArray// is the same length as the toTrim array. If there are no spaces to trim a copy of// the toTrim array should be made to the newArray.If the toTrim array has no characters// then the newArray should have no cahracters(a null termination only).


{
int i,j,spaces=0;
if(strlen(toTrim)==0)
{
newArray[0] = '\0';//if the char array is itself empty, the trimmed output would also be empty
}
for(i=strlen(toTrim)-1;i>=0;i--)
{
if(toTrim[i]==' ')
{
spaces++;// traverse the character array backwards and count the number of spaces it ends with
}
else
{
break;
}
}
if(spaces == strlen(toTrim))
{
newArray[0] = '\0'; // if the array is completely spaces, then the output array would be empty
}
for(i=0;i<(strlen(toTrim)-spaces);i++)
{
newArray[i]=toTrim[i]; //assigning the output array the values of the original array until just before the spaces in the end.
}
}
try something like this.

if(input == 0) return 0; //null pointer input.
strcpy(output, input);
int e = strlen(input) -1; //e is the index of the last character.
while(input[e] == ' ')
output[e] = 0;
return output;


Topic archived. No new replies allowed.