0

Текст самого задания: Отредактировать заданное предложение, удаляя из него все слова с нечетными номерами и переворачивая слова с четными номерами.
Вот мой код:

public static void DelSubStr(ref string s)
{
    int count = 1;
    foreach (string ch in s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
    {
        if (count == 1)
        {
            s = s.Remove(0, s.Length);
        }
        if (count % 2 == 0)
        {
            s += ReverseString(ch);
            s += " ";
        }
        count++;
    }
}
public static string ReverseString (string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}

Препод сказал сделать тоже самое, только без использования подстроки. Как это можно сделать, подскажите пожалуйста)

2 ответа 2

1

Ну, например, вот так

public static string DelSubStr(string s)
{
    var sb = new StringBuilder();
    var stack = new Stack<char>();
    var curr = 0;
    while (curr < s.Length)
    {           
        while (curr < s.Length && s[curr] == ' ') curr++;
        while (curr < s.Length && s[curr] != ' ') curr++;
        while (curr < s.Length && s[curr] == ' ') curr++; 
        while (curr < s.Length && s[curr] != ' ')
        {
            stack.Push(s[curr]);
            curr++;
        }
        if (stack.Count > 0 && sb.Length > 0) sb.Append(' ');
        while (stack.Count > 0) sb.Append(stack.Pop());
    }
    return sb.ToString();
}

Проверка

Console.WriteLine(DelSubStr("   nechotnoe  chotnoe   nechotnoe    chotnoe   "));

Ожидаемо выводит

eontohc eontohc
0

Даешь linq-однострочник

public static string DelSubStr(string s)
{
    return string.Join(" ", s.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
            .Where((x, i) => i % 2 == 0)
            .Select(x => new string(x.Reverse().ToArray())));
}

Проверка

Console.WriteLine(DelSubStr("    nechotnoe     chotnoe     nechotnoe   chotnoe   "));

Результат

eontohc eontohc

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.