Replace consecutive characters with same single character

后端 未结 5 2573
执笔经年
执笔经年 2021-02-20 05:58

I was just wondering if there is a simple way of doing this. i.e. Replacing the occurrence of consecutive characters with the same character.

For eg: - if my string is \

5条回答
  •  野的像风
    2021-02-20 06:31

            Console.WriteLine("Enter any string");
            string str1, result="", str = Console.ReadLine();
            char [] array= str.ToCharArray();
            int i=0;
            for (i = 0; i < str.Length;i++ )
            {
              if ((i != (str.Length - 1)))
              { if (array[i] == array[i + 1]) 
                {
                    str1 = str.Trim(array[i]);
                }
                else
                {
                    result += array[i];
                }
              }
              else
              {
              result += array[i];
              }                    
            }
            Console.WriteLine(result);
    

    In this code the program ;

    1. will read the string as entered from user

    2.Convert the string in char Array using string.ToChar()

    1. The loop will run for each character in string

    2. each character stored in that particular position in array will be compared to the character stored in position one greater than that . And if the characters are found same the character stored in that particular array would be trimmed using .ToTrim()

    3. For last character the loop will show error of index out of bound as it would be the last position value of the array. That's why I used * if ((i != (str.Length - 1)))*

    6.The characters left after trimming are stored in result in concatenated form .

提交回复
热议问题