I cannot express how clean and easily understandable your code was. I liked it so much that i took it as my base code. I added a few more lines and now the function is working perfectly, taking out excess whitespace as well as new lines and horizontal tabs.
Here have a look:
Code:
int cleanSpace( char s[])
{
int i = 0, j = 0, // general loop index
first = 0, // first non-whitespace character
last = 0; // last non-whitespace character
// loop to find the first non-whitespace character
// and save its position as 'first'.
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] != 32 && s[i] != 9 && s[i] != 10)
{
first = i;
break;
}
}
// loop to find the last non-whitespace character
// and save its position as 'last'.
for (i = strlen(s) - 1; i > first; i--)
{
if (s[i] != 32 && s[i] != 9 && s[i] != 10)
{
last = i;
break;
}
}
// for loop to copy all characters in string 's'
// between 'first' & 'last' to string 's'.
for (i = 0; first <= last ; i++)
{
s[i] = s[first];
first++;
}
s[i] = '\0';
//for loop to find and replace white space characters
//with spaces.
for(i = 0; i < strlen(s) + 1; i++)
{
if (s[i] >= 9 && s[i] <= 10)
{
s[i] = 32;
}
}
//for loop to remove excess whitespace if there are
//more than one consecutive whitespaces.
i = 0;
while (s[i] != '\0')
{
if(s[i] == 32 && s[i+1] == 32)
{
//Since excess white space was found, we shift
//the whole string so as to take out the
//whitespace, regardless of what character is
//being copied.
for(j = i; s[j] != '\0'; j++)
{
s[j] = s[j+1];
}
}
//If whitespace was not found, we increase index 'i'
//and start looking at the next character.
else {
i++;
}
}
//Return the length of the "NEW" string 's'.
return strlen(s);
}
For everyone who might read, I give full credit to
oogabooga for the code. I only added a few lines!!