How to search for a specific character in a string?

Hi, i'm doing a validation exercise program. Just a question, how do i search an inputted string for a certain character?

For example:
Hello.World

I wanna determine and find out the where the '.' sign is.

I'm doing an if-else conditions, i need to determine where the character is located and make sure it doesn't repeat. Thanks in advance
Last edited on
there is number of way to do that.
you can use regex header file to do that. for validation exercise program this is a important header file.
see http://www.cplusplus.com/reference/regex/ for more info.

// simple other way

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

using namespace std;

int main()
{
    string str{"Hello.World"};
    size_t t=str.find(".");
    if(t!=string::npos){
     cout<<"yes ....."<<endl;

    }else{
     cout<<"no...."<<endl;
    }


  return 0;
}
Cool, thanks that helped me out.

Another thing, how can i determine if the inputted string has a repeated character?
closed account (D80DSL3A)
You could simply iterate through the string letter by letter and report the positions on the fly. Keep count of occurrences so you can report this at the end.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void countGivenChar( const string& str, char givenChar )
{
    unsigned count = 0;
    for( unsigned i=0; i<str.size(); ++i )
    {
        if( str.at(i) == givenChar )// found one!
        {
            if( count == 0 ) cout << givenChar << " was found at position(s): ";// print this only once
            cout << i << ' ';
            ++count;
        }
    }
    if( count == 0 ) cout << "No " << givenChar << " was found.\n"
    // add a line here to report how many times givenChar was found if count != 0.
}


Or, use the find() function to find them all, since one overload lets you specify the starting point in the string to search from:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void countGivenChar( const string& str, char givenChar )
{
    size_t found = 0, N = 0;
    if( (found = str.find( givenChar )) != string::npos )
    {
        cout << "The " << givenChar << " was found at position(s) " << found; ++N;
        while( (found = str.find( givenChar, found+1 )) != string::npos )
        { cout << ", " << found; ++N; }
        cout << "\nfor a total of " << N << " times\n";
    }
    else
        cout << "The " << givenChar << " was not found\n";
}

int main()
{
    string inStr("Hel.llo wo.rld.");
    countGivenChar( inStr, '.' );
    return 0;
}

Output:
The . was found at position(s) 3, 10, 14
for a total of 3 times
Last edited on
Thank you! That gave me an idea.
Topic archived. No new replies allowed.