Search code examples
c++ccstringc-strings

cStrings Remove non-alpha/non-space character - C++


So I need to create a function that removes all non-letter and non-space character characters from a string of characters (c-string).

For example: "I'm upset that on Nov. 15th, 2014, my 2 brand-new BMW 750Lis were stolen!!" should be turned into "im upset that on nov th my brandnew bmw lis were stolen".

documentCopy[201] = "I'm upset that on Nov. 15th, 2014, my 2 brand-new BMW 750Lis were stolen!!";

for (int i = 0; documentCopy[i] != '\0'; i++)
{
    if (!isalpha(documentCopy[i]) && !isspace(documentCopy[i]))
    {

        for (int k = i; documentCopy[k] != '\0'; k++)
        {
            documentCopy[k] = documentCopy[k+1];

        }
    }
}
cout << documentCopy << endl;

Unfortunately the output is "Im upset that on Nov 5th 04 my brandnew BMW 5Lis were stolen!"

Please help!


Solution

  • After One Line After this loop

    for (int k = i; documentCopy[k] != '\0'; k++)
    {
        documentCopy[k] = documentCopy[k+1];
    }
    i--;  //Add This line in your Code.
    

    This will work.

    for example
    if you are checking a[0] and shifting a[0] = a[1]
    So you need to check a[0] again because now it is holding value of a[1] now, so need to decrease the index value.