C# работа с подстрокой

296
27 сентября 2017, 08:01

Как сделать такое задание используя классы (Word, Sentence)?

После каждого слова текста, заканчивающегося заданной подстрокой, вставить указанное слово.

Также, как можно рационализировать логику?

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Enter the text, please.");
        string text = Console.ReadLine();
        Console.WriteLine("Now U can add a word to this text:\n{0}\n", text);
        Console.WriteLine("Enter the substring");
        string substr = Console.ReadLine();
        int substrLength = substr.Length;
        Console.WriteLine("Enter the word to add");
        string wordToAdd = Console.ReadLine();
        int choise;
        bool esc = true;
        do
        {
            Console.Clear();
            Console.WriteLine("1. Show initial text\n2. Show changed text\n3. Enter new substring\n4. Enter new word to add\n0. Exit");
            string tmp = Console.ReadLine();
            bool isNum = int.TryParse(tmp, out choise);
            if (isNum)
            {
                switch (choise)
                {
                    case 1:
                        Console.WriteLine(text);
                        Console.ReadKey();
                        break;
                    case 2:
                        Change(text, substr, wordToAdd, substrLength);
                        Console.ReadKey();
                        break;
                    case 3:
                        Console.WriteLine("Enter the substring");
                        substr = Console.ReadLine();
                        substrLength = substr.Length;
                        break;
                    case 4:
                        Console.WriteLine("Enter the word to add");
                        wordToAdd = Console.ReadLine();
                        break;
                    case 0:
                        esc = false;
                        break;
                    default:
                        Console.WriteLine("Invalid input. Try again");
                        Console.ReadKey();
                        break;
                }
            }
        } while (esc);
    }
    public static void Change(string text, string substr, string wordToAdd, int substrLength)
    {
        string[] split = text.Split(new Char[] {' '});
        foreach (string word in split)
        {
            char lastIndex = Convert.ToChar(word.Substring(word.Length - 1, 1));
            if (word.Contains(substr))
            {
                if (((int)lastIndex >= 33 && (int)lastIndex <= 47) || ((int)lastIndex >= 58 && (int)lastIndex <= 64))
                {
                    if (word.Substring((word.Length - substrLength - 1), substrLength).Equals(substr))
                    {
                        Console.Write("{0} ", word);
                        Console.Write("{0} ", wordToAdd);
                    }
                    else Console.Write("{0} ", word);
                }
                else if (word.Substring((word.Length - substrLength), substrLength).Equals(substr))
                {
                    Console.Write("{0} ", word);
                    Console.Write("{0} ", wordToAdd);
                }
                else Console.Write("{0} ", word);
            }
            else Console.Write("{0} ", word);

        }
    }
}
Answer 1

Мне приходит в голову такое решение:

class Program
{
    static void Main(string[] args)
    {
        /*
         * После каждого слова текста, заканчивающегося заданной подстрокой, вставить указанное слово
         * */
        string text = "abc123. qwe123 rty123, uio123 asd123, fgh456 jkl789. zxc123 vbn258. mp147";
        string substr = "123";
        string wordToAdd = "ddqd";
        string[] words = text.Split();
        for (int i = 0; i < words.Length; i++)
        {
            if (EndsWithAndPunctuation(words[i], substr))
                words[i] = words[i].Insert(words[i].LastIndexOf(substr[substr.Length-1])+1, wordToAdd);
                //words[i] = words[i] + " " + wordToAdd);
        }
        string result = "";
        for (int i = 0; i < words.Length; i++)
        {
            result += words[i] + " ";
        }
        Console.WriteLine(result);
        Console.ReadKey();
    }
    public static bool EndsWithAndPunctuation(string word, string str)
    {
        string[] punctuation = { "", ",", ".", ";", ":", ")", "?", "!", "..." };
        foreach(string punct in punctuation)
        {
            if (word.EndsWith(str + punct))
                return true;
        }
        return false;
    }
}

Закомментированная строка приводит решение к Вашему виду.

На мой взгляд эта логика несколько проще.

READ ALSO
Проблема с загрузкой папок с диска

Проблема с загрузкой папок с диска

Проблем такаяЕсть элемент TreeView, в него при загрузки формы добавляются все диски компьютера(Скриншот ниже)

305
Unity3d - Изменение Text через GetComponent C#

Unity3d - Изменение Text через GetComponent C#

В сцене есть Scrolling Menu которое создает префабы с содержимым Sprite и добавлена кнопка Select и Buy которые активируются в зависимости от текущего...

336
C# | Разделить строку на массив [требует правки]

C# | Разделить строку на массив [требует правки]

Использовать функцию StringSplit():

301
Динамическая подгрузка DLL

Динамическая подгрузка DLL

Допустим, у меня есть метод:

319