Reputation: 69
write a function that returns no value to delete capital letters in a C-string
void erase(char* a) { char* targetp = sourcep;
while (*sourcep != '\0')
{
if (isupper(static_cast<unsigned char>(a)== false)
{
*targetp++ = *sourcep;
}
a++;
}
*a='\0';
}
Upvotes: 0
Views: 531
Reputation: 25623
You should not copy all the text every time you see a upper case letter. You simply skip the upper case letter and copy step by step. See the solution below. It's much faster!
void deleteCapitals(char* sourcep) //a function that only passes
{
char* targetp = sourcep;
while (*sourcep != '\0')
{
if (!isupper(static_cast<unsigned char>(*sourcep)))
{
*targetp++ = *sourcep;
}
sourcep++;
}
*targetp='\0';
}
Upvotes: 4
Reputation: 9725
Everytime two upper case letters are next to each other, you give a pass to the second one.
An alternative to @Bathsheba's solution is to use a while
instead of if
:
while (isupper(*a))
{
for (char* p = a; *p != '\0'; p++)
{
*p = *(p + 1);
}
}
That way if *a
is still uppercase after the reassignment, it does it again.
Upvotes: 0
Reputation: 234805
a++
should not be invoked if you have deleted a letter. Use an else
to implement that.
Else you'll skip over letters, and your algorithm will fail for cases where there are consecutive capitals.
Also *p != '\0'
can be abbreviated to simply *p
. Not to everyone's taste but it's what I do.
Upvotes: 4