-
-
Save unilecs/465c9dc04b4f84e335c8f2a548f36ae1 to your computer and use it in GitHub Desktop.
Задача 136. Custom String.IndexOf()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
// Метод расширения для типа String | |
public static class StringExtension | |
{ | |
// Кастомная реализация метода String.IndexOf() | |
// Возвращаем кортеж Tuple<int, int>, | |
// где первый параметр - 1е вхождение заданного символа, второй параметр - последнее вхождение | |
public static Tuple<int, int> CustomIndexOf(this string str, char symbol) | |
{ | |
int firstIndex = -1, lastIndex = -1, count = 0; | |
for (int i = 0; i < str.Length; i++) | |
{ | |
if (str[i] == symbol) | |
{ | |
if (count == 0) | |
{ | |
firstIndex = i; | |
} | |
else | |
{ | |
lastIndex = i; | |
} | |
count++; | |
} | |
} | |
lastIndex = lastIndex == -1 ? firstIndex : lastIndex; | |
return new Tuple<int, int>(firstIndex, lastIndex); | |
} | |
} | |
public class Program | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine("UniLecs"); | |
Console.WriteLine(string.Format("Answer = {0}", "AbcAde".CustomIndexOf('A'))); // (0, 3) | |
Console.WriteLine(string.Format("Answer = {0}", "bbcAde".CustomIndexOf('A'))); // (3, 3) | |
Console.WriteLine(string.Format("Answer = {0}", "bbcdef".CustomIndexOf('A'))); // (-1, -1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment