PDA

View Full Version : Function to return index of a specified character


dsm1995gst
04-09-2003, 11:56 PM
I'm looking for a function that I can use to search a string for a certain character, and return the index of that character when it finds it.

I found something called indexOf, but I can't seem to get it to work right.

edit - BTW, this is to be used in C++.

djdante97
04-10-2003, 01:27 AM
#include <string.h>
char *strchr(const char *s, int c);

Jason
04-10-2003, 02:27 AM
http://www.utilitycode.com/str/doc/default.htm
link to an answer you might be interested in...


Jason

dsm1995gst
04-10-2003, 05:11 AM
This is my problem. I have to let the user enter a sentence, and then I have to output how many words are in the sentence, and the number of occurrences of each letter. The number of words is easy, I can't get the number of occurrences of each letter part. This is what I have:

#include <iostream>
#include <string>

using namespace std;


// CS227HW5Correct.cpp : Defines the entry point for the console application.

const int SIZE = 27;

int main()
{
char abcArray[SIZE] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'};

int counter = 0;

string line;
int wordCount = 1;
int i;

cout << "Enter a sentence using only letters or punctuation (no numbers): " << endl;
getline(cin, line);
//cout << "***repeating output as test: " << line << endl;

// counts number of words in the sentence
for (i = 0; i < line.length(); i++)
{
if (line[i] == ' ' || line[i] == '.')
wordCount++;
}

// counts number of occurrences of each letter
for (i = 0; i < SIZE; i++)
{
if (line.find(abcArray[i]) != -1)
{

counter++;

if (line.find(abcArray[i], ????????) != -1)
{
counter++;
}
cout << counter << abcArray[i] << endl;
}
counter = 0;
}

cout << endl << endl;
cout << "The length of the line of text you entered is " << line.length() << endl;
cout << "The number of words in the text you entered is " << wordCount << endl;




return 0;
}

dsm1995gst
04-10-2003, 05:17 AM
The area in question is in bold. I put a bunch of Question Marks in the spot I need help in.

I can find the first occurrence of a letter easily by using the function str.find(char1).

There is also another function that I can use: str.find(char1, pos). Using this function, you can put a position as the second argument so that the search will start there. This is exactly what I need to do, I need to start a search at the first occurrence of the letter so that I can see if there are any more occurrences. The only problem is, I have no way of getting the index of the first occurrence so that I can plug it in as the second argument.

dsm1995gst
04-11-2003, 01:32 AM
Nevermind, I am an idiot. The str.find() function actually does return the index.