You can either keep strtrimws
as a separate function or incorporate its contents within your Students::removeSpace
function. The following function can be used with or without assigning the return. Examples: strtrimws (somestring);
or char *newstring = strtrimws (somestring);
Also note, while the original string 's' is modified by the function, the start address for 's' is unchanged making it safe for use with dynamically allocated strings. Shown below in context with your removeSpace
function:
#include <ctype.h>
/** remove leading and trailing whitespace, original not preserved.
* this funciton can be used with or without assigning the return.
*/
char *strtrimws (char *s)
{
char *sp = s; /* start pointer to return */
char *p = s; /* pointer to parse string */
while (isspace (*s)) s++; /* skip leading whitespace */
while (*s) *p++ = *s++; /* reindex s to end */
while (isspace (*p)) *p-- = 0; /* null-terminate from end */
return sp;
}
char **storeArray;
void Students::removeSpace()
{
int i = 0;
for(int i=0; i<3; i++)
strtrimws (storeArray[i]);
}
NOTE: if you have initialized all pointers to zero/NULL
in storeArray
before assigning strings to (some or all) of the pointers-to-char
you can simplify/improve removeSpace
by eliminating the hardcoded number of iterations for i
and replacing it with a simple:
void Students::removeSpace()
{
int i = 0;
while (storeArray[i])
strtrimws (storeArray[i++]);
}
Example of funciton in use:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/** remove leading and trailing whitespace, original not preserved.
* this funciton can be used with or without assigning return.
*/
char *strtrimws (char *s)
{
char *sp = s; /* start pointer to return */
char *p = s; /* pointer to parse string */
while (isspace (*s)) s++; /* skip leading whitespace */
while (*s) *p++ = *s++; /* reindex s to end */
while (isspace (*p)) *p-- = 0; /* null-terminate from end */
return sp;
}
int main (int argc, char **argv)
{
if (argc < 2) {
fprintf (stderr, "\n error: insufficient input. Usage: %s char* char* ... (max 5)\n\n", argv[0]);
return 1;
}
char array[5][50] = {{0}};
int i = 0;
for (i = 1; i < argc; i++)
{
strncpy (array[i-1], argv[i], strlen (argv[i]));
printf ("\n array[%d] '%s'\n", i, strtrimws (array[i-1]));
}
return 0;
}
output:
$ ./bin/stripwsarray " string 1 ws " " string 2 ws " " string 3 ws "
array[0] 'string 1 ws'
array[1] 'string 2 ws'
array[2] 'string 3 ws'