C # Learning 05 -- IndexOf,

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.