Search code examples
c#fileopenfiledialog

How to check if file contains strings, which will double repeat sign?


I would like to check if file containing some strings, separated with # contains double repeat sign. Example: I have a file like this:

1234#224859#123567

I am reading this file and putting strings separated with # it into array. I would like to find which strings have a digit repeated next to each other (in this case 224859) and return position of first digit that repeats in this string?

This is what I have so far:

    ArrayList list = new ArrayList();
    OpenFileDialog openFile1 = new OpenFileDialog();

        int size = -1;
        DialogResult dr = openFile1.ShowDialog();
        string file = openFile1.FileName;
        try
        {
            string text = File.ReadAllText(file);
            size = text.Length;
            string temp = "";

            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] != '#')
                {
                    temp += text[i].ToString();
                }
                else
                {
                    list.Add(temp);
                    temp = "";
                }
            }
        }
        catch (IOException)
        {
        }
        string all_values = "";
        foreach (Object obj in list)
        {
            all_values += obj.ToString() + " => ";

            Console.WriteLine(" => ", obj);
        }
        textBox1.Text = (all_values);

Solution

  • This is a more procedural approach than Sriram's, but the main benefit is remembering your results in order to use them later in your program.

    Basically, the string is split based on the # delimiter, which returns a string[] which holds each number inside. Then, for each string you iterate through the characters and check to see if the current character at i matches the next character at i + 1. If so, the earliest appearance of a duplicate digit is at i, so i is remembered and we break out of the loop that processes chars.

    Since int is a non-nullable type, I decided to use -1 to indicate that a match was not found in a string.

    Dictionary<string, int> results = new Dictionary<string, int>();
    string text = "1234#224859#123567#11#4322#43#155";
    string[] list = text.Split('#');
    foreach (string s in list)
    {
        int tempResult = -1;
        for (int i = 0; i < s.Length - 1; i++)
        {
            if(s.ElementAt(i) == s.ElementAt(i + 1))
            {
                tempResult = i;
                break;
            }
        }
        results.Add(s, tempResult);
    }
    
    foreach (KeyValuePair<string, int> pair in results) 
    {
        Console.WriteLine(pair.Key + ": " + pair.Value);
    }
    

    Output:

    1234: -1

    224859: 0

    123567: -1

    11: 0

    4322: 2

    43: -1

    155: 1