How to remove all non-numeric characters from a string in C++

3 Answers

0 votes
#include <iostream>
 
char *RemoveCharacters(char* s);
 
int main()
{
    char s[] = "123c++ 9982programming 10000000000001language";
     
    std::cout << RemoveCharacters(s) << std::endl;
 
    std::cout << s << std::endl;
 
    return 0;
}
char *RemoveCharacters(char* s)
{
    char *dest = s;
    char *src = s;
 
    while (*s)
    {
        if (!isdigit(*s)) { s++; continue; }
        *dest++ = *s++;
    }
    *dest = '\0';
 
    return src;
}
 
 
/*
run:
 
123998210000000000001
123998210000000000001
 
*/

 



answered Jan 31, 2017 by avibootz
edited 14 hours ago by avibootz
0 votes
#include <iostream>
 
void RemoveCharacters(char* s);
 
int main()
{
    char s[] = "123c++ 9982programming 10000000000001language";
     
    RemoveCharacters(s);
 
    std::cout << s << std::endl;
 
    return 0;
}
void RemoveCharacters(char* s)
{
    char *dest = s;
 
    while (*s)
    {
        if (!isdigit(*s)) { s++; continue; }
        *dest++ = *s++;
    }
    *dest = '\0';
}
 
 
/*
run:
 
123998210000000000001
 
*/
 

 



answered Jan 31, 2017 by avibootz
edited 14 hours ago by avibootz
0 votes
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

/**
 * @brief Removes all non-numeric characters from a string, returning a new filtered string.
 * 
 * @param input The original string containing alphanumeric and special characters.
 * @return std::string A new string containing only numeric digits (0-9).
 */
[[nodiscard]] std::string extractNumericOnly(const std::string& input) {
    // Create a copy of the input string to modify and return
    std::string result = input;

    // C++20 std::erase_if removes all elements that satisfy the predicate (returns true)
    std::erase_if(result, [](unsigned char c) {
        // Return true if the character is NOT a digit (meaning it gets erased)
        return !std::isdigit(c);
    });

    return result;
}

int main() {
    // Optimize standard I/O operations for performance
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

    // Test string provided
    std::string text = "123c++ 9982programming 10000000000001language";

    // Process the string
    std::string cleanedText = extractNumericOnly(text);

    // Output results
    std::cout << "Original: " << text << "\n";
    std::cout << "Cleaned:  " << cleanedText << "\n";
}



/*
run:

Original: 123c++ 9982programming 10000000000001language
Cleaned:  123998210000000000001

*/

 



answered 14 hours ago by avibootz

Related questions

...