Fini
Fini

Reputation: 9

C# - Add to stuff to each textbox line till a specific character

So, I'm working on a code beautifier and I need some help.

When there's an opening bracket { I want every line after that to have 4 spaces in front of them till the closing bracket }. I've managed to do it for the line after with string.Replace("{", "{" + Environment.NewLine + " "), but that's not enough.

Also how would I got about handling semicolons ;, because sometimes they have a space after them and sometimes not. I can do this: string.Replace(";", ";" + Environment.NewLine, but when there's a space after the semicolon the space moves to the second line so it looks bad, I can check for ; and ; *space* and replace both, but then it creates an empty line if there is a space.

Thanks for the help, idk if my explanation was understandable, but I hope you know what I mean :D

Upvotes: 0

Views: 112

Answers (3)

kame
kame

Reputation: 21970

  1. Look for all ; and make a line break.
  2. Delete all trailing spaces.
  3. Do the step that Pol suggested.

Upvotes: 0

Javier Conde
Javier Conde

Reputation: 2593

You will need a nesting counter so you will introduce 4 spaces at the beginning as many times as it is indicated in the nesting counter.

You should increase the counter each time you find the character '{' and decrease it when you find '}'. Also, I'd make sure those curved brackets are not surrounded by quotes so they are actual code and they don't belong to some string.

About the semicolons, you should just try: Regex regex = new Regex(";\\s*"); regex.Replace(string, ";" + Environment.NewLine);

Upvotes: 1

Pol
Pol

Reputation: 306

For your first question, try something like this:

while(!lines[i].Contains("}")) {
    lines[i].Insert(0,"    ");
    i++;
}

If you want to handle more than one level of curly braces you could do something like this:

int level;
for(int i = 0; i < lines.Length; i++) {
    if(lines[i].Contains("{") level++;
    if(lines[i].Contains("}") level--;
    for(int j = 0; j < level; j++) lines[i].Insert(0, "    ");
}

For your second question, I believe it is a problem with the order of your operations. If you replace semicolon by semicolon + line break alone you will carry the space to the next line. If you replace the semicolon + space for semicolon + line break and then the semicolon for semicolon + line break you will have double lines. What you want to do is to replace semicolon + space for semicolon (namely remove all of the spaces) and then replace semicolon for semicolon + break line.

Hope it helps

Upvotes: 1

Related Questions