S
S
Sleytar2020-05-28 17:45:32
C++ / C#
Sleytar, 2020-05-28 17:45:32

How to find the index of a repeating element in a List?

The task is:
to remove all extra (if several in a row) spaces from a given string.
5ecfcd643cc01007999770.png
In my code, on each pass, it gives the index of the first occurrence of the specified element, and the index of the current one is needed.

The question is simple, but I started to study programming quite recently. Haven't found a solution yet.

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
edward_freedom, 2020-05-28
@Sleytar

Try like this The second option for your initial knowledge
Regex.Replace(str, "[ ]+", " ")

public class Word
    {
        public Word(int index)
        {
            Index = index;
        }

        public int Index { get; set; }
    }

var text = "Мама    мыла  папу + big            space!";
            const char findWord = ' ';
            var wordsDictionary = new List<List<Word>>();

            var count = 0;
            var words = new List<Word>();
            for (var index = 0; index < text.Length; index++)
            {
                var word = text[index];
                if (word == findWord)
                {
                    words.Add(new Word(index));
                    count++;
                }
                else if(count > 0 && word != findWord)
                {
                    wordsDictionary.Add(new List<Word>(words));
                    words.Clear();
                    count = 0;
                   
                }
            }

            wordsDictionary.Reverse();

            foreach (var lettersList in wordsDictionary)
            {
                lettersList.Reverse();
                text = lettersList.Skip(1).Aggregate(text, (current, letter) => current.Remove(letter.Index, 1));
            }

            MessageBox.Show(text);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question