C# String LastIndexOf() Method
In the C# LastIndexOf() method is used to find index position of the last occurrence of a specified character within String or It finds the location of the last occurrence of a letter or substring.
Syntax
Parameter
ch: It is a character type parameter which is used to finds the location of the last occurrence of a letter or substring.
Return
It returns integer value.
Example
The LastIndexOf() method returns the index position of the last occurrence of a specified character or string within the given string.
Output
C# String LastIndexOf() With startIndex and count
C# String IndexOf() vs LastIndexOf() Example
The IndexOf() method returns the index number of the first matched character whereas the LastIndexOf() method returns index number of the last matched character.
C# String LastIndexOf()
In this tutorial, we will learn about the C# String LastIndexOf() method with the help of examples.
The LastIndexOf() method returns the index position of the last occurrence of a specified character or string within the given string.
Example
LastIndexOf() Syntax
The syntax of the string LastIndexOf() method is:
Here, LastIndexOf() is a method of class String .
LastIndexOf() Parameters
The LastIndexOf() method takes the following parameters:
- value — substring to seek
- startIndex — starting position of the search. The search proceeds from startIndex toward the beginning of the given string .
- count — number of character positions to examine.
- comparisonType — enumeration values that specifies the rules for the search
LastIndexOf() Return Value
- returns the index of the last occurrence of the specified character/string
- returns -1 if the specified character/string is not found.
Example 1: C# String LastIndexOf() With startIndex
Output
Notice the line,
- c — char to seek
- 2 — starting index of search (search starts from index 2 towards the beginning of str )
Example 2: C# String LastIndexOf() With startIndex and count
Output
searches 2 characters ( ‘e’ and ‘r’ ) from index 5 towards the beginning of the str string.
C# LastIndexOf() method
In C#, the LastIndexOf() method of String class determines the index of the last occurrence of a character or a String within the invoked String object..
Note: The LastIndexOf performs a case-sensitive search.
Some versions of the LastIndexOf() method
Methods | Description |
---|---|
LastIndexOf(char ch) | It returns the last index of a char ch found in the String object. |
LastIndexOf(char ch, int index) | It returns the last index of a char value(if found) in the String object. The search starts at a specified index position and proceeds backwards toward the beginning of the invoked String. |
LastIndexOf() method returns -1 if the searched char/string(passed to this method) is not found in the invoked String object.
Example of LastIndexOf(char) method
In the upcoming example, we are going to search for the last index of a particular char value in the invoked String object by using the LastIndexOf() method. If the searched char is found, its last index is returned, otherwise if the char is not found then -1 is returned.
Output is :
Program Analysis
-
String is initialized with value Let us decode CSharp!
- The Last occurrence of char value e in the String object is found at index 12.
- The Last occurrence of char value d in the String object is found at index 11.
- The last occurrence of char value z in the String is not found, hence -1 is returned.
- The Last occurrence of char value x in the String is not found, therefore, -1 is returned.
- The Last occurrence of char value ! in the String object is at index 20.
Example of LastIndexOf(char char, int startIndex) method
In the upcoming example, we are going to discuss a different overloaded version of lastIndexOf method i.e. LastIndexOf(char, int), which returns the last index of a char value(if found) in the String object. The search starts at a specified index position and proceeds backwards toward the beginning of the invoked String.
Output is :
Example of LastIndexOf(String) method.
In this next example, we are going to discuss another version of LastIndexOf method i.e. LastIndexOf(String), which searches for the last index of a particular String value in the invoked String object.
Output is :
Program Analysis
-
String is initialized with value Blue Sky Blue
- The last occurrence of the String Blue in the String object is found at the index 9.
- The last occurrence of the String Sky in the String object is found at the index 5.
- The last occurrence of the String Hi in the String object is not found, hence -1 is returned.
Example of LastIndexOf(String str, int startIndex) method
In the upcoming example, we are going to discuss a different overloaded version of lastIndexOf method i.e. LastIndexOf(String, int), which returns the last index of a String value(if found) in the String object. The search starts at a specified index position and proceeds backwards toward the beginning of the invoked String.
Output is :
You must remember that the LastIndexOf() method performs a case-sensitive search and therefore, the LastIndexOf() method has returned -1 when searching for the String live(with a lowercase ‘l’), starting from the index 6 proceeding backwards to the beginning of the invoked String.
Example of LastIndexOf(String, StringComparison)
In the upcoming code, we are going to explain another overload of LastIndexOf method i.e. LastIndexOf(String, StringComparison), which determines the last index of a String value(if found) in the String object. The search is performed on the basis of the specified field of type StringComparison Enum.
The StringComparison is an Enum which specifies culture, sort, case rules to be used by whem the comparison is made between String objects. Its all important 6 fields are explained below.
Note: The LastIndexOf(String, StringComparison) method performs a case-sensitive search, unless you pass a specific field of StringComparison with IgnoreCase specified in it.
C#. Урок 5. Работа со строками
Тема работы со строками является одной из значимых при изучении любого языка программирования. В приведенном материале будут рассмотрены как базовые концепции работы со строками, так и расширенные возможности, предоставляемые C#.
Исходный код примеров из этой статьи можете скачать из нашего github-репозитория.
Знакомство со строками в C#
За представление строк в C# отвечает класс System . String . В коде, для объявления переменной соответствующего типа, предпочтительно использовать следующий вариант написания: string – с маленькой буквы. Это ключевое слово языка, используя которое можно объявлять строковые переменные, также как int является псевдонимом для System.Int32 , а bool – для System.Boolean .
Допустимо объявление строковых переменных через ключевое слово var :
Для объединения строк используется оператор +:
При работе со String следует помнить, что при переопределении значения переменной создается новый экземпляр строковой переменной в памяти. Поэтому, если вам нужно собрать строку из большого количества составляющих, то использование оператора + не самый лучший вариант. В этом случае будет происходить перерасход памяти: при выполнении операции объединения с присваиванием для очень большого количества подстрок, приложение может аварийно завершиться из-за того, что сборщик мусора не будет успевать удалять неиспользуемые объекты, а новые будут продолжать появляться с большой скоростью. Для решения этой задачи используйте StringBuilder , о нем будет рассказано в конце этого урока.
Создание и инициализация объекта класса String
Существует несколько способов создать объект класса String и проинициализировать его. Рассмотрим варианты, которые доступны в C# . Наиболее распространенный способ сделать эту операцию – это присвоить строковое значение переменной без явного вызова конструктора, так, как мы это делали в предыдущем разделе:
Для дословного представления строки, для того чтобы проигнорировать управляющие последовательности, используйте префикс @ перед значением. Сравните вывод следующей конструкции:
Если требуется подготовить строковое значение с использованием набора переменных, то можно воспользоваться статическим методом Format класса String , либо префиксом $ :
Можно явно вызвать конструктор типа c передачей в него параметров. Самый простой вариант – это передать строку:
В качестве параметра может выступать массив Char элементов:
Ещё вариант – это указать элемент типа char и количество раз, которое его нужно повторить:
Для создания строки также можно использовать указатели на Char* и SByte* , но в данном уроке эта тема рассматриваться не будет.
Базовый API для работы со строками
В рамках данного раздела рассмотрим наиболее интересные и полезные методы и свойства класса String .
Объединение строк. Оператор +, методы Concat и Join
Сцеплять строки между собой можно с помощью оператора + , при этом, в результате объединения, будет создан новый объект:
В составе API , который предоставляет System . String , есть метод Concat , который может выполнять ту же работу:
Метод Concat позволяет объединить до четырех строк через прямое перечисление. Если нужно таким образом объединить больше строковых переменных и значений, то используйте оператор +. Полезным свойством Concat является то, что он может принять на вход массив элементов типа String и объединить их:
Для объединения элементов с указанием разделителя используется метод Join . В предыдущем примере, элементы в массиве sArr1 уже содержали пробел, это не всегда удобно, решим задачу объединения элементов, которые не содержат разделителей, с помощью Join :
В качестве разделителя можно использовать любую строку:
Поиск и извлечение элементов из строки. Оператор [], методы IndexOf, IndexOfAny, LastIndexOf, LastIndexOfAny, Substring
Для получения символа из строки с конкретной позиции можно использовать синтаксис подобный тому, что применяется при работе с массивами – через квадратные скобки []:
Для решения обратной задачи: поиск индекса первого (последнего) вхождения элемента или сроки в данной строке используются методы IndexOf , IndexOfAny и LastIndexOf , LastIndexOfAny .
В таблице ниже перечислены некоторые из предоставляемых System . String вариантов этих методов.
IndexOf(Char)
Возвращает индекс первого вхождения символа.
IndexOf(Char, Int32)
Возвращает индекс первого вхождения символа начиная с заданной позиции.
IndexOf(Char, Int32, Int32)
Возвращает индекс первого вхождения символа начиная с заданной позиции, проверяется указанное количество элементов.
IndexOf(String)
IndexOf(String, Int32)
IndexOf(String, Int32, Int32)
Назначение методов совпадает с перечисленными выше, но поиск выполняется для строки.
IndexOfAny(Char[])
IndexOfAny(Char[], Int32)
IndexOfAny(Char[], Int32, Int32)
Назначение методов совпадает с перечисленными выше, но выполняется поиск индекса первого вхождения любого из переданных в массиве элементов.
Last IndexOf([Char | String])
Last IndexOf ( [Char | String], Int32)
Last IndexOf ( [Char | String], Int32, Int32)
Возвращает индекс последнего вхождения символа или строки. Можно задавать индекс, с которого начинать поиск и количество проверяемых позиций. [Char | String] – означает Char или String
LastIndexOfAny(Char[])
LastIndexOfAny(Char[], Int32)
LastIndexOfAny(Char[], Int32, Int32)
Возвращает индекс последнего вхождения любого из переданных в массиве элементов.Можно задавать индекс с которого начинать поиск и количество проверяемых позиций
Для определения того, содержит ли данная строка указанную подстроку, а также для проверки равенства начала или конца строки заданному значению используйте методы: Contains , StartsWith и EndsWith .
Contains(Char)
Contains(String)
Возвращает True если строка содержит указанный символ или подстроки.
StartsWith(Char)
StartsWith(String)
Возвращает True если строка начинается с заданного символа или подстроки.
EndsWith(Char)
EndsWith(String)
Возвращает True если строка заканчивается на заданный символ или подстроку.
Задачу извлечения подстроки из данной строки решает метод SubString :
Substring(Int32)
Возвращает подстроку начиная с указанной позиции и до конца исходной строки.
Substring(Int32, Int32)
Возвращает подстроку начиная с указанной позиции с заданной длины.
Сравнение срок
Для сравнения строк можно использовать оператор сравнения ==, при этом будут сравниваться значения строковых переменных, а не их ссылки, как это делается для других ссылочных типов.
Для сравнения также можно использовать метод Equals , но это менее удобный вариант:
Модификация срок
Класс String предоставляет довольно большое количество инструментов для изменения строк.
Вставка строки в исходную в заданную позицию осуществляется с помощью метода Insert :
Для приведения строки к заданной длине с выравниванием по левому (правому) краю с заполнением недостающих символов пробелами используются методы PadLeft и PadRight :
Метод Remove удаляет подстроку из исходной строки. Возможны два варианта использования:
Remove(Int32)
Удаляет все символы начиная с заданного и до конца строки.
Remove(Int32, Int32)
Удаляет с указанной позиции заданное число символов.
Замена элементов строки производится с помощью метода Replace . Наиболее часто используемые варианты – это замена символа на символ и строки на подстроку:
Для преобразования строки к верхнему регистру используйте метод ToUpper() , к нижнему – ToLower() :
За удаление начальных и конечных символов отвечают методы, начинающиеся на Trim (см. таблицу ниже).
Удаляет символы пробелы из начала и конца строки.
Удаляет экземпляры символа из начала и конца строки.
Удаляет экземпляры символов из начала и конца строки.
TrimStart()
TrimStart(Char)
TrimStart(Char[])
Удаляет экземпляры символов из начала строки.
TrimEnd()
TrimEnd(Char)
TrimEnd(Char[])
Удаляет экземпляры символов из конца строки.
Методы и свойства общего назначения
Рассмотрим некоторые из полезных методов и свойств, которые не вошли в приведенные выше группы.
System.Length – возвращает длину строки:
System.Split() – разделяет заданную строку на подстроки, в качестве разделителя используется указанный через параметр символ (или группа символов):
System.Empty – возвращает пустую строку.
Форматирование строк
Под форматированием строк, в рамках данного раздела, понимается встраивание в строку различных элементом (число, дата и т.п.), представленных в заданном формате. Форматирование можно осуществлять с помощью метода ToString с передачей в него нужных описателей, метода Format , который, в качестве аргументов, получает строку со специальными вставками, определяющими представление элементов и непосредственно сами элементы.
Для начала рассмотрим на нескольких примерах работу с этими методоми:
Эта функциональность также доступна для методов StringBuilder . AppendFormat , TextWriter . WriteLine , Debug . WriteLine , методов из Trace , которые выводят текстовые сообщения, например: Trace . TraceError и метод TraceSource . TraceInformation .
Каждый элемент форматирования представляется следующим образом:
где index – это индекс элемента, которым будет замещена данная конструкция;
alignment – выравнивание;
formatString – формат.
Ниже приведены примеры использования элементов форматирования:
Представление чисел
Для представления чисел используются следующие описатели формата (список не полный, более детальную информацию можете найти в официальной документации):
C# String LastIndexOf()
In this tutorial, we will learn about the C# String LastIndexOf() method with the help of examples.
The LastIndexOf() method returns the index position of the last occurrence of a specified character or string within the given string.
Example
LastIndexOf() Syntax
The syntax of the string LastIndexOf() method is:
Here, LastIndexOf() is a method of class String .
LastIndexOf() Parameters
The LastIndexOf() method takes the following parameters:
- value — substring to seek
- startIndex — starting position of the search. The search proceeds from startIndex toward the beginning of the given string .
- count — number of character positions to examine.
- comparisonType — enumeration values that specifies the rules for the search
LastIndexOf() Return Value
- returns the index of the last occurrence of the specified character/string
- returns -1 if the specified character/string is not found.
Example 1: C# String LastIndexOf() With startIndex
Output
Notice the line,
- c — char to seek
- 2 — starting index of search (search starts from index 2 towards the beginning of str )
Example 2: C# String LastIndexOf() With startIndex and count
Output
searches 2 characters ( ‘e’ and ‘r’ ) from index 5 towards the beginning of the str string.
C# String LastIndexOf() Method
In the C# LastIndexOf() method is used to find index position of the last occurrence of a specified character within String or It finds the location of the last occurrence of a letter or substring.
Syntax
Parameter
ch: It is a character type parameter which is used to finds the location of the last occurrence of a letter or substring.
Return
It returns integer value.
Example
The LastIndexOf() method returns the index position of the last occurrence of a specified character or string within the given string.
Output
C# String LastIndexOf() With startIndex and count
C# String IndexOf() vs LastIndexOf() Example
The IndexOf() method returns the index number of the first matched character whereas the LastIndexOf() method returns index number of the last matched character.
Array.LastIndexOf Method in C# | Set – 1
Array.LastIndexOf method is used to find the last matching element in a one-dimensional array. It starts the search from the last element of an array. It returns the index of the element that contains the specified value. There are 6 methods in the overload list of this method as follows:
- LastIndexOf(Array, Object)
- LastIndexOf(Array, Object, Int32)
- LastIndexOf(Array, Object, Int32, Int32)
- LastIndexOf<T>(T[], T)
- LastIndexOf<T>(T[], T, Int32)
- LastIndexOf<T>(T[], T, Int32, Int32)
Here we discuss only the first three methods.
LastIndexOf(Array, Object)
This method searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.
Syntax: public static int LastIndexOf (Array arr, object value);
Parameters:
arr: It is the one-dimensional Array to search.
value: It is the object to locate in array.
Return Value: If the index of value is found then, this method returns the index of the last occurrence of that value within the entire array. If not found then, the lower bound of the array minus 1.
- ArgumentNullException: If the array arr is null.
- RankException: If the array arr is multidimensional.
Example 1:
Example 2:
LastIndexOf(Array, Object, Int32)
This method searches for the specified object and returns the index of the last occurrence within the range of elements in the one-dimensional Array that extends from the first element to the specified index.
Syntax: public static int LastIndexOf (Array arr, object value, int start);
Parameters:
arr: It is the one-dimensional Array to search.
value: It is the object to locate in array.
start: It is the starting index of the backward search.
Return Value: If the index of value is found then, this method returns the index of the last occurrence of that value within a range of elements in array “arr that extends from the first element to start. If not found then, the lower bound of the array minus 1.
Exceptions:
- ArgumentNullException: If the array arr is null.
- RankException: If the array arr is multidimensional.
- ArgumentOutOfRangeException: If “start” index is outside the range of valid indexes for array.
Example 1:
Example 2:
LastIndexOf(Array, Object, Int32, Int32)
This method searches for the specified object and returns the index of the last occurrence within the range of elements in the one-dimensional array that contains the specified number of elements and ends at the specified index.
Syntax: public static int LastIndexOf (Array arr, object value, int start, int count);
Parameters:
arr: It is the one-dimensional Array to search.
value: It is the object to locate in array.
start: It is the starting index of the search.
count: It is the number of elements in the section to search.
Return Value: If the index of value is found then, this method returns the index of the last occurrence of that value within a range of elements in array “arr” that contains the number of elements specified in “count” and ends at “start” index. If not found then, the lower bound of the array minus 1.
C# LastIndexOf() method
In C#, the LastIndexOf() method of String class determines the index of the last occurrence of a character or a String within the invoked String object..
Note: The LastIndexOf performs a case-sensitive search.
Some versions of the LastIndexOf() method
Methods | Description |
---|---|
LastIndexOf(char ch) | It returns the last index of a char ch found in the String object. |
LastIndexOf(char ch, int index) | It returns the last index of a char value(if found) in the String object. The search starts at a specified index position and proceeds backwards toward the beginning of the invoked String. |
LastIndexOf() method returns -1 if the searched char/string(passed to this method) is not found in the invoked String object.
Example of LastIndexOf(char) method
In the upcoming example, we are going to search for the last index of a particular char value in the invoked String object by using the LastIndexOf() method. If the searched char is found, its last index is returned, otherwise if the char is not found then -1 is returned.
Output is :
Program Analysis
-
String is initialized with value Let us decode CSharp!
- The Last occurrence of char value e in the String object is found at index 12.
- The Last occurrence of char value d in the String object is found at index 11.
- The last occurrence of char value z in the String is not found, hence -1 is returned.
- The Last occurrence of char value x in the String is not found, therefore, -1 is returned.
- The Last occurrence of char value ! in the String object is at index 20.
Example of LastIndexOf(char char, int startIndex) method
In the upcoming example, we are going to discuss a different overloaded version of lastIndexOf method i.e. LastIndexOf(char, int), which returns the last index of a char value(if found) in the String object. The search starts at a specified index position and proceeds backwards toward the beginning of the invoked String.
Output is :
Example of LastIndexOf(String) method.
In this next example, we are going to discuss another version of LastIndexOf method i.e. LastIndexOf(String), which searches for the last index of a particular String value in the invoked String object.
Output is :
Program Analysis
-
String is initialized with value Blue Sky Blue
- The last occurrence of the String Blue in the String object is found at the index 9.
- The last occurrence of the String Sky in the String object is found at the index 5.
- The last occurrence of the String Hi in the String object is not found, hence -1 is returned.
Example of LastIndexOf(String str, int startIndex) method
In the upcoming example, we are going to discuss a different overloaded version of lastIndexOf method i.e. LastIndexOf(String, int), which returns the last index of a String value(if found) in the String object. The search starts at a specified index position and proceeds backwards toward the beginning of the invoked String.
Output is :
You must remember that the LastIndexOf() method performs a case-sensitive search and therefore, the LastIndexOf() method has returned -1 when searching for the String live(with a lowercase ‘l’), starting from the index 6 proceeding backwards to the beginning of the invoked String.
Example of LastIndexOf(String, StringComparison)
In the upcoming code, we are going to explain another overload of LastIndexOf method i.e. LastIndexOf(String, StringComparison), which determines the last index of a String value(if found) in the String object. The search is performed on the basis of the specified field of type StringComparison Enum.
The StringComparison is an Enum which specifies culture, sort, case rules to be used by whem the comparison is made between String objects. Its all important 6 fields are explained below.
Note: The LastIndexOf(String, StringComparison) method performs a case-sensitive search, unless you pass a specific field of StringComparison with IgnoreCase specified in it.