Найти в строке самое длинное слово без split, для типа string, не используя методов класса - C#
Формулировка задачи:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication28
{
class Program
{
static void Main(string[] args)
{
const string str = "Найдите в ней самое длинное слово";
string[] arr = str.Split(' ');
string maxWord = string.Empty;
foreach (string s in arr)
if (maxWord.Length < s.Length)
maxWord = s;
Console.WriteLine("Самое длинное слово: {0}, его длинна = {1}", maxWord, maxWord.Length);
Console.ReadLine();
}
}
}Решение задачи: «Найти в строке самое длинное слово без split, для типа string, не используя методов класса»
textual
Листинг программы
class Program
{
private static void Main(string[] args)
{
string str = ",123,546,879,454,";
foreach (var word in str.MySplit(new []{',','.',' '}))
{
Console.WriteLine( "_{0}_",word);
}
Console.ReadLine();
}
}
public static class MyClass
{
public static string[] MySplit(this string str, char[] separators,bool withEmpty = false)
{
if (separators == null) throw new ArgumentNullException("separators");
if (str == null) throw new ArgumentNullException("str");
if (separators.Length == 0) throw new ArgumentException("Массив пустой");
if (string.IsNullOrWhiteSpace(str)) throw new ArgumentException("Строка пустая");
var list = new List<string>();
int start=-1, end=0;
string substr = string.Empty;
for (int i = 0; i < str.Length; i++)
{
if (!separators.Contains(str[i]))
continue;
// если текущий символ есть в массиве разделителей
end = i;
substr = str.Substring(start + 1, end - start - 1);
if (!withEmpty)
{
// если опция без пустых строк то не копируем если строка пустая
if (!string.IsNullOrWhiteSpace(substr))
list.Add(substr);
}
else
{
list.Add(substr);
}
start = end;
}
substr = str.Substring(end + 1, str.Length - end - 1);
if (!withEmpty)
{
// если опция без пустых строк то не копируем если строка пустая
if (!string.IsNullOrWhiteSpace(substr))
list.Add(substr);
}
else
{
list.Add(substr);
}
return list.ToArray();
}
}