Zerowalker Zerowalker - 19 days ago 5
C# Question

Format Text(Code), removing spaces and stuff

I want to make it so each code will Always look the same no matter if you use 100 spaces etc.

So for example

Example: lwz r4,-0x0018(rtoc)


This is how the code should look, and here is examples of how it Could be inputed.

lwz r4, -0x0018 (rtoc)
lwz r4,-0x0018(rtoc)
lwz r4,-0x0018 (rtoc)


There are other codes as well, but i think the general rule is.

(No Space around",". And "No space around "(" and ")" ).

As this will get looped many times through lines, the method should preferably be quite fast.

I am not against using unsafe code etc:)

Thanks!

EDIT:

Code can also be like: "fmul f0,f1,f2" and same thing applies there.

What i have tried is looking through it as a pointer (unsafe).
But while i can replace character i can't remove them per say.
I guess i have to do without pointers, but i still am not sure how to figure out the rules for the loop even though i kinda grasp it. (the ifs etc to format).

EDIT2:

This is the current Messy code i seem to have gotten to work.

private string FormatCode(string text)
{

int length = text.Length;

char last = '.';

for (int i = 0; i < text.Length; i++)
{
char c = text[i];

if (c == ' ' && last == ',')
{
text = text.Remove(i, 1);
i--;
}
else if (c == ',' && last == ' ')
{
text = text.Remove(i-1, 1);
i--;
}
else if(c=='(' && last == ' ')
{
text = text.Remove(i - 1, 1);
i--;
}
else if(c == ' ' && last == ')')
{
text = text.Remove(i, 1);
i--;
}
else if (c == ' ' && last == ' ')
{
text = text.Remove(i, 1);
i--;
}

last = c;

}

return text;
}

Answer
var a = "lwz   r4,   -0x0018     (rtoc)";
var b = string.Join(" ", a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries))
    .Replace(" ,", ",").Replace(", ", ",")
    .Replace(" (", "(").Replace("( ", "(")
    .Replace(" )", ")").Replace(") ", ")");

This variant is faster but longer (and does not eliminate a leading space, not sure if it is needed):

var a = "lwz   r4,   -0x0018     ( rtoc )";
StringBuilder sb = new StringBuilder(a.Length);
var spaceFound = false;
var ignoreSpaces = false;
for (int i = 0; i < a.Length; i++)
    if (a[i] == ' ')
        spaceFound = true;
    else if (a[i] == '(' || a[i] == ')' || a[i] == ',')
    {
        sb.Append(a[i]);
        ignoreSpaces = true;
    }
    else
    {
        if (spaceFound && !ignoreSpaces)
            sb.Append(' ');
        sb.Append(a[i]);
        spaceFound = false;
        ignoreSpaces = false;
    }
var b = sb.ToString();