Recursion problem with string

Pages: 12
Can you help me with these two problems with recursion?
1) I have a string : define the dimension
2) I have a string and a character: find the first position of the character in the string
Thanks to all!!

The first I made but it has't recursion....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

C++:

#include <iostream>
using namespace std;
int main() {
   char string[] = "Prova";
   int conta = 0;
   while (string[conta] != 0)
      conta++;
   cout<<"La stringa e' "<<string<<endl;
   cout <<"La lunghezza della stringa e' "<<conta<<endl;
   return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

std::size_t str_size( const char* cstr )
{
    if( cstr == nullptr || cstr[0] == 0 ) return 0 ; // empty string, size == 0
    else return 1 + str_size(cstr+1) ; // 1 (for the first char) + size of the remaining chars
}

int main()
{
    const char cstr[] = "prova" ;
    std::cout << str_size(cstr) << '\n' ;
}
I done so (i dont' know nullptr and also char*) but I have this messagge (""expected primary-expression before 'char') in the line "
cout << lunghezza(string)";


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace std;



int lunghezza(char string)

{



    if (string == 0)

        return 0;

    else

        return 1 + lunghezza(string + 1);

}



int main()

{

    char string[] = "Prova";

    cout << lunghezza(string);

    return 0;

}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int lunghezza( const char string[] )
{
    if ( string[0] == 0 ) return 0;

    else return 1 + lunghezza(string + 1);
}

int main()
{
    const char string[] = "prova" ;
    std::cout << lunghezza(string) << '\n' ;
}
Many thanks!!
Some ideas for the second problem?
Last edited on
That code he posted already solves your second problem. Simply replace 0 in line 5's if statement with the value in the string you're looking for and the function will return it's first position.
Last edited on
Some ideas for the second problem?

A suggestion, a bit funny by demand for recursion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int  cerchiamo( const char ago, const char pagliaio[] )
{
    if ( pagliaio[0] == ago ) return 1;
    if ( pagliaio[0] == 0 ) return -999999999;

    else return 1 + cerchiamo(ago, pagliaio + 1);
}

int main()
{
    char lettera[] = "rx";
    char parola[] = "prova" ;
    int i, t;
    for (i=0; i<2; i++)
    {
        t = cerchiamo(lettera[i], parola);
        if (t < 0)
            cout << "Non trovo '" << lettera[i] << "' in '" << parola << "'";
        else
            cout << "'" << lettera[i] << "' si trova a posizione " << t;
        cout << ".\n";
    }
}

'r' si trova a posizione 2.
Non trovo 'x' in 'prova'.
Thank you MIkeStgt.
Excuse me zapshe can you write the cose, I don'y understand well.
Lets say you wanted to look for the character 'v' -

1
2
3
4
5
6
7
8
9
10
11
12
int lunghezza(const char string[], const char search)
{
	if (string[0] == search) return 0;

	else return 1 + lunghezza(string + 1, search);
}

int main()
{
	const char string[] = "prova";
	std::cout << lunghezza(string, 'v') << '\n';
}


^With the only tweaks being an extra parameter/argument for convenience, this code will print 3. Understand that an array starts at 0, so at element 3 is the letter 'v'.
The teacher didn't teach me "search"...
Is there another method without using an array so the position is real position (for example 'v' is the element 4)?
"search" is simply a variable name.. Look at line 11, I made the variable search = 'v' when it goes into the function lunghezza. And once inside the function in line 5, I can put the variable in as an argument since the function will have a value for "search" is by the time it's called.

You have to use your array if you're going to search through it. The whole point of this assignment is likely to help teach you recursion, which can be used to search through an array (though there are easier and better means).

And element 4 is NOT 'v', it would be 'a'. An array starts at 0. If you were to do this:

std::cout << string[4];

Your output would be 'a', because element 4 is 'a'. If you for some reason want the number of where 'v' visually is, you can simply add 1 to the output of the function:

std::cout << (lunghezza(string, 'v')+1) << '\n';
Thank you for explanation.
There is a method without using array, also for the first problem?
The function can do both. With the slight tweak that I made you can find the element where your letter is. If instead of looking for a letter you look for 0 or NULL, you'll know how large your array is.
@zapshe,
You need to deal with the case where the character is not found or risk hanging your PC. See @MikeStgt's code for one possibility, although this problem is not a good one to do by recursion as you would have to propagate "not found" all the way back up the stack, testing for it all the time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int findPosition( char c, const char *text )
{
   if ( !*text      ) return -1;
   if (  *text == c ) return  0;
   int ans = findPosition( c, text + 1 );
   return ans < 0 ? -1 : ans + 1;
}

int main()
{
   char text[] = "nil desperandum";
   for ( char c : {'a','b','c','d','e'} )
   {
      int pos = findPosition( c, text );
      if ( pos < 0 ) cout << c << " is not found\n";
      else           cout << c << " is first found at (zero-based) position " << pos << '\n';
   }
}
Last edited on
I am searching a simple solution.. similar to this but without mistakes.....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int  cerchiamo( const char a, string b)
{
    if ( b == a ) return 1;
    if ( b == 0 ) return -1;

    else return 1 + cerchiamo(a, string + 1);
}
int main ()
{
    string b;
    cin>> string;
    const char a;
    cin a;
    return 0;
}
Could you fix those mistakes first? That is a good exercise for you.
I made this code, the problem is that i dont't understand well how correct the mistakes....
Last edited on
I made this that's ok , but I wish to do the second problem without array....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include<string>

using namespace std;
int lunghezza (string s)
{if ( s == "")
    return 0;
else
   
    return 1 + lunghezza (s.substr(1));
}
    int main()
{
    string s;
    cin>> s;
    cout<< lunghezza(s);
    return 0;
}
Last edited on
You need to deal with the case where the character is not found or risk hanging your PC. See @MikeStgt's code for one possibility, although this problem is not a good one to do by recursion as you would have to propagate "not found" all the way back up the stack, testing for it all the time.

Yes, I'm just trying to show him the concept first, it seems he's not understanding well.

mpg, you should likely try to practice and solidify your current C++ knowledge, I recommend going to learncpp.com .

Line 16 in your code a few posts ago doesn't have ">>". Line 4 in your recent code is checking if the ENTIRE string "str" is equal to "" - and what is ""? "" isn't anything valid.
Last edited on
I have readden here
https://stackoverflow.com/questions/41425569/checking-for-empty-string-in-c-alternatives
that if I write
string == ""
means that if the string is an empty string , so it hasn't characters and return 0.

I also can write in the line 6
if ( s.length() == 0)

But I don't find a good code without array for the second problem.


Last edited on
Pages: 12