(2019-04-15, 09:01 PM)SimoSbara Wrote: I optimized a bit this code:
Code:for(new i = strlen(text); i >= 0; --i)
{
?if(text[i] == ' ') ?
? ?if(text[i-1] == ' ' || i == 0)
? ? ? ? ? ?strdel(text, i-1, i);
}
The syntax is correct, I?deleted the "spaces" variable because you could check the extra space by comparing the character before the text[i]. Let me know if it works the same.
EDIT: I also removed the switch case just to make the code cleaner.
EDIT 1: Optimized again a case scenario.
Final code:
Code:for(new i = strlen(text); i >= 0; --i)
{
?if(text[i] == ' ')
?{
? ?if(text[i-1] == ' ')
? ? ?strdel(text, i-1, i);
? ?else if(i == 0)
? ? ?strdel(text, 0, 1);
?}
}
What about space at end of sentence?? You deleted at 0 pos and need to delete at strlen pos too
PHP Code:
for(new i = strlen(text); i >= 0; --i)
{? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
?if(text[i] == ' ')
?{
? ?if(text[i-1] == ' ')
? ? ?strdel(text, i-1, i);
? ?else if(i == 0)
? ? ?strdel(text, 0, 1);
? ?else if(i == strlen(text)-1)
? ? ?strdel(text, strlen(text)-1, strlen(text);
?}
}
I think that's will be faster(especially with long sentences):
PHP Code:
for(new i = strlen(text); i >= 0; --i)
{
? ? if(text[i] == ' ')
? ??{
? ? ? ? if(text[i-1] == ' ')
? ? ? strdel(text, i-1, i);
? ? }
}
if(text[0] ==?'?')
strdel(text, 0, 1);
if(text[strlen(text)-1] == ' ')
strdel(text, strlen(text)-1, strlen(text));
![[Image: aWbv5wm.gif]](https://imgur.com/aWbv5wm.gif)