In: Computer Science
Enter a string: "ABC8CBEABC+DE$$"
Enter a character to search: B
Character B is found at the following indices: 1, 5, 8
Enter a character to search: E
Character E is found at the following indices: 6, 12
Enter a character to search: w
Character w is found at the following indices: NONE
Enter a character to search: &
Code:
#include <iostream>
#include <vector>
using namespace std;
void find(string s, char ch)
{
printf("Character %c is found at the following indices: ", ch);
// We declare an Vector of type int to store the indices
vector<int> indices;
// We iterate over the string
for (int i = 0; i < s.length(); i++)
{
// If the character at index i in the string is equal to ch
if (s[i] == ch)
{
// Then we add the index i to the indices vector
indices.push_back(i);
}
}
// If no indices were found for the given character, then we print NONE
if (indices.size() == 0)
{
printf("NONE\n");
}
// Else we print the indices found for the given character
else
{
for (int i = 0; i < indices.size(); i++)
{
printf("%d", indices[i]);
if (i != indices.size() - 1)
{
printf(", ");
}
}
printf("\n");
}
}
int main()
{
printf("Enter a string: ");
// Reading the string from the user
string s;
cin >> s;
// This loop is iterated until an non-alphabetic character is entered by the user
while (true)
{
printf("Enter a character to search: ");
// Reading the character entered by the user
char ch;
cin >> ch;
// If it is alphabetic, then we call the find method.
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
{
find(s, ch);
}
// Else we break the loop
else
{
break;
}
}
return 0;
}
Sample Output: