superkiller170793
superkiller170793

Reputation: 91

Adding spaces between character in a String C#

Well, I've got a propositional logic sentence like this :

~(((-P|-Q)->(P->Q))&((P->Q)->(-P|Q)))  

and what I'd like to do, it's to add spaces between each character; and get something like this:

~ ( ( ( -P | -Q ) -> ( P -> Q ) ) & ( ( P -> Q ) -> ( -P | Q ) ) )  

Moreover; I wouldn't like to add spaces only in those joined character -> and -P because represent an operand and a negative statements. I had found a regular expression which added spaces, but it did it with all the characters, even with those which shouldn't have. this is the expression i had found:

(?<=.)(?!$) 

So; any help for doing it; doesn't matter whether is either a method or the same regular expression but modified.

Upvotes: 1

Views: 2454

Answers (4)

Alex
Alex

Reputation: 35417

string subject = "~(((-P|-Q)->(P->Q))&((P->Q)->(-P|Q)))",
       pattern = @"([\(\)|QP~&]|-P|-Q|->)";

Regex reg = new Regex(pattern);

Console.WriteLine(reg.Replace(subject, "$1 "));

Above code outputs:

~ ( ( ( -P | -Q ) -> ( P -> Q ) ) & ( ( P -> Q ) -> ( -P | Q ) ) )

Regex Pattern Explained:

https://regex101.com/r/b7STUP/2

Upvotes: 1

apocalypse
apocalypse

Reputation: 5884

Version simple to understand:

string initial = "~(((-P|-Q)->(P->Q))&((P->Q)->(-P|Q)))";

string result = string.Join<char> (" ", initial).Replace ("- ", "-");

Upvotes: 2

abdul
abdul

Reputation: 1592

You can use Linq, first Aggregate the string by adding spaces then use Replace to remove the space on the right of each hyphen.

string initial = "~(((-P|-Q)->(P->Q))&((P->Q)->(-P|Q)))";
string result = initial.Aggregate("", (c, i) => c + i + ' ').Replace(" - ", " -").Trim();

Upvotes: 0

David Libido
David Libido

Reputation: 479

Simple thought: -Make a char[] from it -Loop through it to a list adding a space every % 2 -Join the list to a string -Trow a replace over it to convert - > to -> and such

Upvotes: 0

Related Questions