Programming Tips - C/C++: How to delete non-numeric characters from a string

Date: 2009mar28 Update: 2026sep24 Language: C/C++ Q. C/C++: How to delete non-numeric characters from a string A. This is handy if user-entered strings are supposed to be numbers. Use the function DeleteNonNumericCharacters() below:
// Helper function inline char *Shuffle(char *dest, const char *src) { return (char *) memmove(dest, src, strlen(src) + sizeof(char)); } // Helper function inline bool IsNumeric(const char c) { return isdigit(c) || c == '-' || c == '.'; } void DeleteNonNumericCharacters(char *s) { for (char *p = s + strlen(s) - 1; p >= s; p--) { if (!IsNumeric(*p)) { Shuffle(p, p + 1); } } }
Full Example Use:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> // (Place the above functions here) int main() { char buf[100]; strlcpy(buf, "EDT5EST", sizeof(buf)); DeleteNonNumericCharacters(buf); printf("buf=%s<\n", buf); // Now you can safely do atoi() on it: int hours = atoi(buf); printf("hours=%d\n", hours); }
Output:
buf=5< hours=5