### How To Check How Much Characters Are Between Certain Characters

I have a test soon and want to make sure I'm doing these right.

If we have something like this:

code a[10]="la#sdas\$lf"

How would you make sure there are atleast two characters between # and \$.
bump?
If you want to use char arrays, you can write your own find function which loops through the array & returns the position of the found char. Do this for both search chars then subtract.

If you use a C++ string, you can use the find algorithm to do the same thing.

 http://www.cplusplus.com/reference/algorithm/find/

Even though the example is for vectors, you can do the same thing for strings.

Hope all goes well.
That's what i've been trying to do, however, the math isn't correct.
Basically I do something like this:
 ``1234567891011121314151617181920212223`` ``````char code [10] ; cout << "Enter a word with @ first some words then # in it:"; cin.getline(code,10); /*kind@oftwo#la*/ //Make sure there are atleast two characters between @ and # //Find position of @ for (int i = 0; i < 10; i ++) { string[i] = @; } //Find position of # for (int j = 0; j < 10; j ++) { string[j] = #; } int place; place = string[j] - string[i]; // to find how much characters This doesn't work though..hmmm ``````
 ``1234`` ``````for (int i = 0; i < 10; i ++) { string[i] = @; //assignment }``````

This doesn't work because the assignment has to be a small int (0 to 255) or a char with single quotes.

What you need is:

 ``12345678`` ``````unsigned short Position@ = 0; for (int i = 0; i < 10; i ++) { if (string[i] == '@') //comparison, note the single quote for a char Position@ = i; } ``````

Hope this helps
Last edited on
It would be much more useful if you would show a code snip that can be compiled. Where is the magic name string defined in your code?!!!

If you are using a charater array it is natural to use standard C functions for character arrays

 ``1234`` ``````char *p, *q; int n = 0; if ( ( p = strchr( code, '@' ) ) && ( q = strchr( code, '#' ) ) ) n = abs( p - q ) - 1;``````
Last edited on
It would be more correctly to write the following way

 ``123456789`` ``````char *p, *q; int n = 0; if ( ( p = strchr( code, '@' ) ) && ( q = strchr( code, '#' ) ) ) { if ( q < p ) std::swap( p, q ); while ( *p == *( p + 1 ) ) ++p; n = abs( p - q ) - 1; }``````
Last edited on
And one more solution.:)

 ``12345678910`` ``````char *p, *q; int n = 0; char s[] = "##A#B@@"; if ( ( p = strchr( s, '@' ) ) && ( q = strchr( s, '#' ) ) ) { if ( q < p ) std::swap( p, q ); p = std::find( std::reverse_iterator( q ), std::reverse_iterator( p ), *p ).base(); n = abs( p - q ); }``````
Last edited on
Topic archived. No new replies allowed.