looking for char in string

i have to look for all the char possible in string and get those char position but can't seem to figure out how look for all char. i tried using str.find but it only looks for the first one in whole string
I assume you mean you want to count all occurrences of a particular character in a string? If so, do something like this...

1
2
3
4
5
6
7
8
9
10
11
12
string x = "This is a test.";
char searchItem = 't';
int numOfChar = 0;
int length = strlen(x);

for(int  i = 0;i < length;i++)
{
    if(x[i] == searchItem)
    {
        numOfChar++;
    }
}


Whereas "numOfChar" would be the integer that stores the number of occurrences of that character and "searchItem" would be the char you're looking for. To check for both the uppercase and lowercase instances of that particular letter, just make it check for the char converted using tolower() and the char converted using toupper().
Last edited on
You can move inside a string with subscript operator or iterators and get all the characters contained.
Can you explain better what you need?
im sorry i wasn't clear i don't wanna know the occurrences for char but position of char. for example
string my_string= "blasddsdfsl"
and i want to search for char 'd'. i want to know the position of every char 'd' in that string
closed account (3hM2Nwbp)
And how would you want that data represented? In an array / vector?
because the second string holds blanks '-' for every char in first string "blasddsdfsl" and after i search for char in that string i have to replace that char with blanks in that second string. u get it?
closed account (3hM2Nwbp)
So essentially you're replacing every occurrence of a character with another? If so, this can be done in a loop similar to what PacketPirate posted about 5 posts up.
but don't i have to know the position of where that character is found to be able to replace it in second string at that same position?
closed account (3hM2Nwbp)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Code by PacketPirate
string x = "This is a test.";
string x2 = x;
char searchItem = 't';
char replacement = '-';
int length = strlen(x);

for(int  i = 0;i < length;i++)
{
    if(x[i] == searchItem)
    {
        //set x2[i] to the replacement
    }
}
Last edited on
yup like that but the other way around lol. but i got it thanks
Topic archived. No new replies allowed.