Question regardig indexof(string, int32, int32)

J

Jorge Rojas

I have a question. I'm dealing with indexof and I got a behaviour I never
expected...

From documentation,

public int IndexOf (
string value,
int startIndex,
int count
)

should return the "count" occurrence of search after start.

Am I wrong?

The code (c#):

/******/
string aSearch;
int aPos;
aSearch = "This is a dumb test, a simple test for testing a test
I want to test";
aPos = aSearch.IndexOf("test", 2, 1);
/******/

I got aPos= -1 ??? How???

Another:
/******/
aSearch = "This is a dumb test, a simple test for testing a test
I want to test";
aPos = aSearch.IndexOf("test", 1, 1);
/******/

I got aPos = -1 again...

The only one that works is aString.IndexOf(search, index) Any ideas? What I
am doing wrong?
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Jorge said:
I have a question. I'm dealing with indexof and I got a behaviour I
never expected...

From documentation,

public int IndexOf (
string value,
int startIndex,
int count
)

should return the "count" occurrence of search after start.

Where did you get that idea?
Am I wrong?

Yes.

The count argument determines how many characters in the string is
searched. It's searching in the string that you would get by using
aSearch.Substring(startIndex, count).

Or as the documentation says:

"count - The number of character positions to examine."
The code (c#):

/******/
string aSearch;
int aPos;
aSearch = "This is a dumb test, a simple test for testing a
test I want to test";
aPos = aSearch.IndexOf("test", 2, 1);
/******/

I got aPos= -1 ??? How???

Because you are looking in a part of the string that is only one
character long. You can hardly find a four character string inside a one
character string.
Another:
/******/
aSearch = "This is a dumb test, a simple test for testing a
test I want to test";
aPos = aSearch.IndexOf("test", 1, 1);
/******/

I got aPos = -1 again...

The only one that works is aString.IndexOf(search, index) Any ideas?
What I am doing wrong?

Not reading the documentation properly... ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top