I have a string that is actually a Y86-64 instruction set:
rmmovq %r0 , 0 ( %rB)
So I want to remove extra spaces from it and convert it to:
rmmovq %r0, 0(%rB)
I have tried lots of things, but I am out of option now. Help please!
What have you tried? You could try something like
for (int i = 0; myString[i] != '\0'; i++) {
if (myString[i] == " ")
while (myString[i+1] == " ")
for (int j = i + 1; myString[j] != '\0'; j++)
myString[j] = myString[j+1];
}
I have not verified that it is portable, works well, etc.
This will just reduce down to single spaces. If you know your data absolutely will conform to a specific pattern, you can probably add in a bunch of special logic, but the code gets very fragile very fast in that case.
You probably want regex, but that’s not directly part of vanilla C.
The best I got was this:
int i, x;
for (i = x = 0; str[i]; ++i)
if (!isspace(str[i]) || (i > 0 && !isspace(str[i - 1])))
str[x++] = str[i];
str[x] = '\0';
But it was still leaving one blank space before comma and brackets.
Woops, I meant myString
instead of line
.
Eliminating the extra spaces in
rmmovq %r0 , 0 ( %rB)
is what I mean about wanting to put in extra special logic that’s somewhat fragile.
// Strip multiple spaces
for (int i = 0; myString[i] != '\0'; i++) {
if (isSpace(myString[i]))
while (isSpace(myString[i+1]))
for (int j = i + 1; myString[j] != '\0'; j++)
myString[j] = myString[j+1];
}
// Strip space before commas
for (int i = 0; myString[i] != '\0'; i++) {
if (isSpace(myString[i]))
if (myString[i+1] == ",")
for (int j = i; myString[j] != '\0'; j++)
myString[j] = myString[j+1];
}
// Strip space before and after (
for (int i = 0; myString[i] != '\0'; i++) {
if (isSpace(myString[i]))
if (myString[i+1] == "(") {
myString[i] = myString[i + 1]
for (int j = i + 1; myString[j] != '\0'; j++)
myString[j] = myString[j+2];
}
}
Again, not checked, optimized, etc, just rough thoughts. Without regex this will end up being pretty fragile code.
1 Like
Well, this works, I mixed your code and mine, and I got the result.

1 Like
Working is the first step to clean and pretty : )