What Is String.IndexOf() In C#?
Có thể bạn quan tâm
Overview
In C#, the String.IndexOf() is a string method used to find the location of a character or substring within the String object.
Syntax
There are multiple overloaded versions of the String.IndexOf() method in C#. The most common syntaxes of this method are as follows:
// find the location of a character // within a string objectString.IndexOf(char ch, int startIndex);// find the location of a substring // within a string objectString.IndexOf(string substring, int startIndex);syntax for IndexOf() methodParameters
- char ch: This is a character whose index position is to be found.
- string substring: This is a string whose index position is to be found.
- int startIndex: This is an optional parameter. It represents the starting position for the search. Its default value is 0.
Return value
This method returns an integer corresponding to the zero-based index of the first occurrence of the specified string or character within this instance. If not found, it returns a value of -1.
Exception
- ArgumentNullException: This exception is thrown when the source string or character's index position is null.
- ArgumentOutOfRangeException: This exception is thrown when the startIndex parameter value is less than zero or greater than the length of the string.
Example
In the example below, we'll use the IndexOf method to search for a particular character within a string.
using System; public class Example { //Main method starts execution of C# code examples public static void Main() { string str = "this is a string example"; Console.WriteLine(str.IndexOf('a')); } }RunExplanation
- Line 7: First, we create a string variable str to hold our source string.
- Line 8: Next, we'll call the IndexOf method, passing in the character we want to search for. In this case, we're looking for the character 'a' within the string str.
The IndexOf method will return the index of where that character was found. In this example, it would return 8, since 'a' appears at position 8 in string str.
Relevant Answers
Explore Courses
Free Resources
License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)Từ khóa » Hàm Indexof Trong C#
-
Hướng Dẫn Và Ví Dụ C# String Và StringBuilder - Openplanning
-
Indexof() Lấy Chỉ Số Từ Một String - Cộng đồng C Việt
-
String.IndexOf Method (System) - Microsoft Docs
-
Chuỗi (String) Trong C# - Học Lập Trình C# Online - VietTuts
-
Tổng Hợp Các Hàm Xử Lý Chuỗi Trong Lập Trình C# » Chia Sẻ để Vui Vẻ
-
C# | String.IndexOf( ) Method | Set - 1 - GeeksforGeeks
-
Lớp String Trong Lập Trình C# Căn Bản | How Kteam
-
Hàm IndexOf() Trong JavaScript | Học Lập Trình JavaScript
-
Chuỗi (String) Trong C#
-
Hàm dexOf() Trong Javascript - Freetuts
-
Phương Thức IndexOf() Trong Java String - Freetuts
-
C# - Is There A Function Equivalent To "String.IndexOf(String[])"?
-
C# IndexOf - Linux Hint
-
Working Of C# String IndexOf() With Examples - EduCBA