Home > Software design >  C how can I check if a string contains a special character, then a specific character after?
C how can I check if a string contains a special character, then a specific character after?

Time:09-29

I'm a beginner programmer trying to have a user enter an email in a text field. In the text field I would like to:

A) Ensure the user has entered an @ symbol somewhere in the field
B) Ensure the user has entered a . somewhere after their @ symbol

Is there some way to do this? I'm having a hard time looking for my own answers online because of how specific it seems.

Thanks for any help!

CodePudding user response:

You can use std::string:

std::string::size_type position = text_field.find(special_char);
if (position != std::string::npos)
{
   // special char is found.
   if (position   1 < text_field.length())
   {
       if (text_field[position   1] == specific_char)
       {
            // Specific char found.
       }
   }
}

You may want to make a copy of the text field data type into a std::string before using the above code.

CodePudding user response:

To check for a specific character, use

std::string text = "whatever text @ something.com";

auto pos = std::find(text.begin(), text.end(), '@');

If '@' appears somewhere in text, pos will point at the location of the first occurrence.

Having done that, to search for another character that follows the first one, just use the same approach, starting at the position of the first character:

auto res = std::find(pos, text.end(), '.');

If both searches succeeded, res will point at the first '.' after the first '@'. If either search failed, it will point past the end of the string:

if (res == text.end()) 
    std::cout << "match failed\n";
else
    std::cout << "success\n";

CodePudding user response:

Meme

If my memory serves me, then the true regular that checks for the validity of E-Mail takes 100500 lines, you decide you really need to check whether the e-mail is valid, or does it just meet your deep subjective requirements? But i still tried to make it a REGEX.

#include <iostream>
#include <regex>
#include <string>
 
bool CheckEmail(const std::string &str)
{
    return std::regex_match(str, std::regex("([\\w-\\.] )@((?:\\w \\.) )([a-zA-Z]{2,4})"));
}
 
int main()
{
    std::cout << std::boolalpha << CheckEmail("[email protected]") << std::endl;
}

will be useful ...

https://docs.microsoft.com/en-us/cpp/standard-library/regex-functions?view=msvc-160

https://en.cppreference.com/w/cpp/regex

https://www.youtube.com/watch?v=9K4N6MO_R1Y

  • Related