Find a string in an array

Alright so lets say I need to find a certain string in an array that has many different strings. how would i do a search of that array for a certain string? also, it needs to tell me which array it is in.

thanks for any help
Last edited on
Create a for loop to cycle through all of your array elements, you need to test each element for the desired string the way you do that will depend on the type of variable used to represent the string.

If it's a character string (char[x]), you can compare two strings using strcmp(...), you can find information about it here: http://www.cplusplus.com/reference/clibrary/cstring/strcmp/

If it's a string class object (string sMyString) you can use string::compare(...), you can find information about it here: http://www.cplusplus.com/reference/string/string/compare/

If a match to the desired string is found then return the index (or store it's value in an integer for reference later).

I hope this helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int findNumber(int array[], int size, int target);

int main()
{
	
	int mynumbers[] = {1,2,3,4,5};
	int arraysize = sizeof(mynumbers) / sizeof(int);
	int target = 3;
	cout << findNumber(mynumbers,arraysize,target);
	char y;
	cin >> y;
	return 0;
}

int findNumber(int array[], int size, int target){
	for(int counter = 0;counter<size;counter++){
		if(array[counter] == target){
			return counter;
		}
	}
}


that's how I made it, and it works great. but am i doing this the long way or is this good?
the application you wrote above is fine, but in your initial question you wrote:

PinheadLarry wrote:
find a certain string in an array
So I assumed you wanted to do some string comparisons.
Yes, i do also need to do comparisons.

so lets say it reads the file and in the arrays there are:

teststrings[1] == "1234"
teststrings[2] == "123"

how would I have it search for 123, and not pick the 1234?

i hope i explained that okay
use strcmp(...); or string::compare(...);.

For example:

Using strcmp(...),
bool fStringMatch = ( strcmp(teststrings[1], "123") == 0 );

Using string::compare(...),
bool fStringMatch = ( teststrings[1]->compare("123") == 0 );
Topic archived. No new replies allowed.