Having difficulty with recursion. Reversing a string and only printing the lower case letters.
Hi all, I'm really struggling with recursion and can't figure out how to reverse a string when I'm not given a defined length. For example, if I had a defined length, then I can swap the last letter of the string with the first and keep calling until the length is 1 or 0. In my case, I have to do the same thing but without a defined length, which basically means I need to go through the string until I find the terminating character "\0". Now I can use a while loop and calculate the amount it takes to get there, but I think that size is constantly changing when the function is called again, and I can't wrap my head around it.
Here's what I have so far.
reversed_letters(const char *str)
{
if(*(str) == '\0')
{
}
else
{
//want to print only the lower case letters
//and swap them in reverse
if(*str >= 'a' && *str <= 'z')
{
reversed_letters(str + 1);
}
//Want to just skip the index in array
else
{
#include <iostream>
#include <cctype>
// get a pointer to the last character of the string
constchar* ptr_last_char( constchar* cstr )
{
// empty string, return nullptr
if( cstr == nullptr || cstr[0] == 0 ) returnnullptr ;
// get to the null character at the end of the string
constchar* ptr = cstr ;
while( *ptr != 0 ) ++ptr ;
return ptr-1 ; // return pointer to character just before the null character
}
void print_lowercase_reverse( constchar* cstr )
{
constchar* ptr = ptr_last_char(cstr) ;
if( ptr != nullptr )
{
while( ptr >= cstr ) // for each character up to the first character
{
// if this character is a lower case character, print it out
if( std::islower( (unsignedchar)*ptr ) ) std::cout << *ptr ;
--ptr ; // get to the next character in reverse direction
}
std::cout << '\n' ; // finally, print a new line
}
}
void print_lowercase_reverse_recursive( constchar* first, constchar* last )
{
// if the last character is a lower case character, print it out
if( std::islower( (unsignedchar)*last ) ) std::cout << *last ;
if( first == last ) std::cout << '\n' ; // reached the end, print a new line
// otherwise, repeat for the next character in reverse direction
else print_lowercase_reverse_recursive( first, last-1 ) ;
}
void print_lowercase_reverse_2( constchar* cstr )
{
constchar* last = ptr_last_char(cstr) ;
if( last != nullptr ) print_lowercase_reverse_recursive( cstr, last ) ;
}
int main()
{
constchar cstr[] = "AbCd efGHijKL MNOpqrSTUvwxYZ!" ;
print_lowercase_reverse(cstr) ;
print_lowercase_reverse_2(cstr) ;
}