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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 
1
2
3
4
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:

1
2
3
4
5
6
7
8
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

1
2
3
4
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


1
2
3
4
5
6
7
8
9
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.:)

1
2
3
4
5
6
7
8
9
10
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<char *>( q ), std::reverse_iterator<char *>( p ), *p ).base();
	n = abs( p - q );
}
Last edited on
Topic archived. No new replies allowed.