Hi guys.
I am a student who really needs some assistance with creating a recursive function in C that changes multiple consecutive white spaces (blanks) from an array of characters into a single blank. For instance:

char c [10]; // let ␢= blank symbol
where the contents are :␢␢␢␢INT␢␢␢
the outcome should be ␢INT␢
NOTE: I somehow need to keep track of the size of the array for actual latter access.

I really suck at recursion and I know that I must first establish a BASE CASE, where the recursion eventually stops, but came up with nothing serious. I am thinking maybe that the recursive call should start as soon as the first blank is identified, and from there remove the blanks. The base case will be the identification of a character other than a blank or reached the end of the array.
THANKS FOR ANY HELP
ALEX.

3
Contributors
5
Replies
19
Views
4 Years
Discussion Span
Last Post by deceptikon

You'll have to recurse one time more than you want to, to find the next char, THEN if it's 'I' don't remove the 'b' you were checking out on the earlier depth. Otherwise, remove it.

Likewise, if you recurse one depth and find the end of the string, then don't remove the space or 'b' you're currently on.

Think of it just like a while() loop, but the recursive part of it, handles the "while" (the looping). The base case should be quite similar to the stop for a while loop.

VERY smart to use 'b' instead of an empty space (which is tough to work with in a visual sense).

Give it a try and see what you can come up with.

is this the equivalent of what you meant? please modify if needed, and if you do please explain why.

``````RemoveBlanks(char c,int i) //assuming same contents as before, and i=0 initially
{
if( (int) c[i] == 32 && c[i+1] != 32)
{
//remove blank here and update size
RemoveBlanks(c, i+1);
}
else if(i <= c.size() )
RemoveBlanks(c, i+1);
}
``````

THANKS AGAIN
ALEX

You could take the easy way out and use a loop to handle removing the blanks, though I suspect your assignment wants recursion to handle everything:

``````void compact(char *s)
{
if (!s[0] || !s[1]) {
// Fewer than 2 characters left in the string
return;
}

if (isspace(s[0]) && isspace(s[1])) {
// Shift-overwrite the current whitespace character
for (int i = 0; s[i]; i++) {
s[i] = s[i + 1];
}

compact(s);
}
else {
compact(s + 1);
}
}
``````

yeah it would be really easy not to use recursion at all. I just wanted to improve my recursion skills.
Thanks for the assistance anyway.
Alex

yeah it would be really easy not to use recursion at all.

It is using recursion, just not 100% recursion.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.