C # Learning 05 -- IndexOf,
Use of IndexOf ()
Example: Find the specified string
String str = "loolloolol"; int index = 0; // index int count = 0; // number of times string keyword = "ol"; // specify the string if (index <str. length) {// The position to be searched cannot be greater than the string Length while (index = str. indexOf (keyword, index ))! =-1) {count ++; Console. writeLine ("{0} appears, index is {1}", count, index); index + = keyword. length; // start from the next position of the index.} else {Console. writeLine ("specified string not found");} Console. readKey ();
You can define a string variable 'str' to search for a specified string 'ol 'in 'str'. If 'ol' is found, the number of times 'Count' appears and the position 'index' appear are output, if no string is found, "specified string not found" is output ".
Str. IndexOf (keyword, index), IndexOf () function will return an index location, if not found, return-1.
Index location! =-1 indicates that the specified string, count + 1, is found, and the index value is assigned to the index. The output "appears count times, index is index ".
In this example, index = 3 and count = 1 after the first execution. After the result is output, the index value for the next query is index = index (the location found this time) + keyword. length (specify the Length of the string), so that you can directly skip the specified string that has been found and start searching from the next position.
The output result is as follows:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.