Reputation: 23
I have the next question. If I have, for example, the next CharArray: {!( !A && A) ( !A && !A )} The problem here is that I want to delete the all '!' that is next to 'A' and add '!' to the 'A' that doesn't have it in the initial CharArray. So the final result of that problem need to be: {!( A && !A ) ( A && A )}
I've tried to use this to delete the '!': //Regla is the string that contains {!( !A && A) ( !A && !A )}
`char[] array = Regla.ToCharArray();
for (int i = 0; i < array.Length; i++)
{
char c = array[i];
if (c == idL1 && array[i - 1] == '!')
{
if (cont1 == 0 && cont2 == 0)
{
var tRegla = new StringBuilder(Regla);
tRegla.Remove(i - 1, 1);
Regla = tRegla.ToString();
cont1++;
}
if (cont1 == 1 && cont2 == 1)
{
var tRegla = new StringBuilder(Regla);
tRegla.Remove(i - 2, 1);
Regla = tRegla.ToString();
cont1++;
}
if (cont1 == 2 && cont2 == 2)
{
var tRegla = new StringBuilder(Regla);
tRegla.Remove(i - 3, 1);
Regla = tRegla.ToString();
cont1++;
}
if (cont1 == 3 && cont2 == 3)
{
var tRegla = new StringBuilder(Regla);
tRegla.Remove(i - 4, 1);
Regla = tRegla.ToString();
cont1++;
}
cont2++;
}`
But at the moment to add a '!' I have a lot of problem, because the counter 'i' changes and I use sompething like:
`var tRegla = new StringBuilder(Regla);
tRegla.Insert(i - 1, "!");
Regla = tRegla.ToString();
cont1++;}`
I think there is a better way to solve it. Thank you.
Upvotes: 1
Views: 527
Reputation: 370
Do you have to use a char array to do this? Seems to me you could just do this instead:
Regla.Replace("A", "!A").Replace("!!A", "A");
It replaces all instances of the letter A
with !A
, so instead of !A
and A
you have !!A
and !A
. Then it replaces all !!A
with just A
, which should be the exact opposite of the original.
To make this work with any capital letter, you'd need to use Regex.Replace
instead.
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var Regla = "{!( !A && A) ( !A && !A )}";
var output = Regex.Replace(Regla, "([A-Z])", "!$1").Replace("!!", "");
Console.WriteLine(output);
}
}
This is a bit more complicated... the regular expression puts the letter inside of (), which makes it a capture group
. Then the replace bit adds a !
to $1
, which represents the instance of the matched character inside of the capture group. Then the call to .Replace()
removes any !!
in the string. This will work with any capital letter. If it needs to work with other patterns, just modify the regular expression.
Upvotes: 4