@SulimK1ald

Подсчет гласных букв. Почему ошибки?

static void Main(string[] args)
        {
            string[] array = { "а", "о", "э", "е", "и", "ы", "у", "ё", "ю", "я" };
            int vcounter = 0;

            string itemStr = Console.ReadLine();
            int item = Convert.ToInt32(itemStr);

                foreach (item in array)
                {
                    if (item.Contains("а") || item.Contains("о") || item.Contains("э")
                        || item.Contains("е") || item.Contains("и") || item.Contains("ы")
                        || item.Contains("у") || item.Contains("ё") || item.Contains("ю")
                        || item.Contains("я")) //You can add the other volwes 
                    {
                        vcounter++;
                    }
                    Console.WriteLine("Count of vowels: " + vcounter.ToString());
                }
        }
  • Вопрос задан
  • 656 просмотров
Решения вопроса 1
Casper-SC
@Casper-SC
Программист (.NET)
Вот как-то так можно. Зачем здесь объявление алфавита? Да теперь его можно копипастить в каждый проект, что удобно. И соревнований по максимальной краткости, вроде бы, не объявляли.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>


using System.Collections.ObjectModel;
using System.Globalization;

namespace VowelsCount;

public class Program
{
    static void Main(string[] args)
    {
        var letters = new List<Letter> {
            new ('а', LetterType.Vowel),
            new ('б', LetterType.Consonant),
            new ('в', LetterType.Consonant),
            new ('г', LetterType.Consonant),
            new ('д', LetterType.Consonant),
            new ('е', LetterType.Vowel),
            new ('ё', LetterType.Vowel),
            new ('ж', LetterType.Consonant),
            new ('з', LetterType.Consonant),
            new ('и', LetterType.Vowel),
            new ('й', LetterType.Consonant),
            new ('к', LetterType.Consonant),
            new ('л', LetterType.Consonant),
            new ('м', LetterType.Consonant),
            new ('н', LetterType.Consonant),
            new ('о', LetterType.Vowel),
            new ('п', LetterType.Consonant),
            new ('р', LetterType.Consonant),
            new ('с', LetterType.Consonant),
            new ('т', LetterType.Consonant),
            new ('у', LetterType.Vowel),
            new ('ф', LetterType.Consonant),
            new ('х', LetterType.Consonant),
            new ('ц', LetterType.Consonant),
            new ('ч', LetterType.Consonant),
            new ('ш', LetterType.Consonant),
            new ('щ', LetterType.Consonant),
            new ('ъ', LetterType.Consonant),
            new ('ы', LetterType.Vowel),
            new ('ь', LetterType.Consonant),
            new ('э', LetterType.Vowel),
            new ('ю', LetterType.Vowel),
            new ('я', LetterType.Vowel)
        };

        var alphabet = new Alphabet(letters);
        IReadOnlySet<char> vowels = alphabet.GetVowelSet();
        IReadOnlySet<char> consonants = alphabet.GetConsonantSet();

        const string text = "Да мы хотим помочь!!!";

        int vowelCounter = 0;
        int consonantCounter = 0;

        var vowelResult = new char[text.Length];
        var consonantResult = new char[text.Length];
        var otherSymbolsResult = new char[text.Length];

        var ruRu = new CultureInfo("ru-RU");

        for (int i = 0; i < text.Length; i++)
        {
            vowelResult[i] = '_';
            consonantResult[i] = '_';
            otherSymbolsResult[i] = '_';

            char lowerCaseChar = char.ToLower(text[i], ruRu);
            if (consonants.Contains(lowerCaseChar))
            {
                ++consonantCounter;
                consonantResult[i] = text[i];
            }
            else if (vowels.Contains(lowerCaseChar))
            {
                ++vowelCounter;
                vowelResult[i] = text[i];
            }
            else
            {
                otherSymbolsResult[i] = text[i];
            }
        }

        Console.WriteLine("Исходная строка для подсчёта:");
        Console.WriteLine(text);
        Console.WriteLine("=========");
        Console.WriteLine(vowelResult);
        Console.WriteLine(consonantResult);
        Console.WriteLine(otherSymbolsResult);
        Console.WriteLine("=========");
        Console.WriteLine("Кол-во символов в исходной строке: " + text.Length);
        Console.WriteLine("Кол-во гласных: " + vowelCounter);
        Console.WriteLine("Кол-во согласных: " + consonantCounter);
        Console.WriteLine("Кол-во прочих символов: " +
            (text.Length - (vowelCounter + consonantCounter)));
    }
}

/// <summary>Тип буквы - гласная или согласная.</summary>
internal enum LetterType
{
    /// <summary>Гласная.</summary>
    Vowel,

    /// <summary>Согласная.</summary>
    Consonant
}

internal record struct Letter(char letter, LetterType type)
{
    public LetterType Type { get; init; } = type;

    public char Value { get; init; } = letter;
}

internal class Alphabet
{
    public IReadOnlyList<Letter> Letters { get; }

    public Alphabet(IEnumerable<Letter> letters)
    {
        Letters = letters switch
        {
            IList<Letter> list => new ReadOnlyCollection<Letter>(list),
            _ => new ReadOnlyCollection<Letter>(letters.ToList()),
        };
    }

    public IReadOnlyList<char> GetVowelList()
    {
        return Letters
            .Where(letter => letter.Type == LetterType.Vowel)
            .Select(letter => letter.Value)
            .ToList()
            .AsReadOnly();
    }

    public IReadOnlySet<char> GetVowelSet()
    {
        return Letters
            .Where(letter => letter.Type == LetterType.Vowel)
            .Select(letter => letter.Value)
            .ToHashSet();
    }

    public IReadOnlyList<char> GetConsonantList()
    {
        return Letters
            .Where(letter => letter.Type == LetterType.Consonant)
            .Select(letter => letter.Value)
            .ToList()
            .AsReadOnly();
    }

    public IReadOnlySet<char> GetConsonantSet()
    {
        return Letters
            .Where(letter => letter.Type == LetterType.Consonant)
            .Select(letter => letter.Value)
            .ToHashSet();
    }
}
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
freeExec
@freeExec
Участник OpenStreetMap
Так у вас логика хромает, вы завели массив гласных и теперь сравниваете, есть ли в этом массиве гласные. Ну бред же.
Ответ написан
KraGenDeveloper
@KraGenDeveloper
Unity Developer
Что то такое
static void Main(string[] args)
        {
            string[] array = { "а", "о", "э", "е", "и", "ы", "у", "ё", "ю", "я" };
            int vcounter = 0;

            string itemStr = Console.ReadLine();
            int item = Convert.ToInt32(itemStr);

                foreach (var item in array)
                {
                    for(int i = 0; i<array.Leght; i++){
                          if(тут типа берёшь item ==  array[i]){
                                  vcounter++;
                          }

                    } 
                    Console.WriteLine("Count of vowels: " + vcounter.ToString());
                }
        }
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы