C++ Check String Contains Number

4 min read Jul 01, 2024
C++ Check String Contains Number

Checking if a String Contains a Number in C++

This article explores different methods for checking if a C++ string contains at least one numerical digit.

1. Using std::any_of with std::isdigit

This approach iterates through each character in the string and uses std::isdigit to check if it's a numerical digit. The std::any_of algorithm returns true if at least one character satisfies the condition.

#include 
#include 
#include 
#include  

bool containsNumber(const std::string& str) {
  return std::any_of(str.begin(), str.end(), { return std::isdigit(c); });
}

int main() {
  std::string str1 = "Hello123";
  std::string str2 = "HelloWorld";

  if (containsNumber(str1)) {
    std::cout << "String 1 contains a number.\n";
  } else {
    std::cout << "String 1 does not contain a number.\n";
  }

  if (containsNumber(str2)) {
    std::cout << "String 2 contains a number.\n";
  } else {
    std::cout << "String 2 does not contain a number.\n";
  }

  return 0;
}

2. Using a loop with std::isdigit

This approach iterates through the string using a loop and checks each character individually using std::isdigit. If a digit is found, the function returns true.

#include 
#include 
#include 

bool containsNumber(const std::string& str) {
  for (char c : str) {
    if (std::isdigit(c)) {
      return true;
    }
  }
  return false;
}

int main() {
  std::string str1 = "Hello123";
  std::string str2 = "HelloWorld";

  if (containsNumber(str1)) {
    std::cout << "String 1 contains a number.\n";
  } else {
    std::cout << "String 1 does not contain a number.\n";
  }

  if (containsNumber(str2)) {
    std::cout << "String 2 contains a number.\n";
  } else {
    std::cout << "String 2 does not contain a number.\n";
  }

  return 0;
}

3. Using regular expressions

This approach uses the std::regex class and a regular expression pattern to find a digit within the string.

#include 
#include 
#include 

bool containsNumber(const std::string& str) {
  std::regex pattern("[0-9]");
  return std::regex_search(str, pattern);
}

int main() {
  std::string str1 = "Hello123";
  std::string str2 = "HelloWorld";

  if (containsNumber(str1)) {
    std::cout << "String 1 contains a number.\n";
  } else {
    std::cout << "String 1 does not contain a number.\n";
  }

  if (containsNumber(str2)) {
    std::cout << "String 2 contains a number.\n";
  } else {
    std::cout << "String 2 does not contain a number.\n";
  }

  return 0;
}

Conclusion

These are just a few ways to check if a C++ string contains a number. The best approach depends on your specific needs and coding style. For simple checks, the loop with std::isdigit method is concise and efficient. For more complex pattern matching, regular expressions provide a powerful tool.