Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created October 29, 2018 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unilecs/465c9dc04b4f84e335c8f2a548f36ae1 to your computer and use it in GitHub Desktop.
Save unilecs/465c9dc04b4f84e335c8f2a548f36ae1 to your computer and use it in GitHub Desktop.
Задача 136. Custom String.IndexOf()
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