简体   繁体   中英

How do I reference the last character of a string without using variable_name.at()?

the code that I'm currently working with looks like this:

if ((text.at(text.size() -1 ) != '!' ) && (text.at(text.size() -1 ) != '?') && (text.at(text.size() -1 ) != ':' ) && (text.at(text.size() -1 ) != ',' ) && (text.at(text.size() -1 ) != ';' ) && (text.at(text.size() -1 ) != '=' ) )

The details of it aren't terribly important but I'm basically trying to make a kind of word processor that only uses the command prompt, and whenever the user presses enter with nothing in the input buffer, the program closes because it's being terminated in "an unusual way" which I'm taking to mean that this line of code is trying to reference a position in the string that doesn't exist, ie -1. So I need a new way to reference the last character in a given string variable that can still work with the line of code given. Thanks for your help!

You should check text is not empty before access its element and use std::string::rbegin or std::string::back(needs C++11) to simplify your code.

you call it this way:

if (!text.empty())
{
    char c = *text.rbegin();
    if (c != '!' && 
        c != '?' && 
        c != ':' && 
        c != ',' && 
        c != ';' && 
        c != '=' )
    {
    }
}

To enhance code readability, you could introduce a local variable in this situation, it's cheap to make a copy of a char and you can shorten your if statement a lot.

Seems easy enough, just check for text.size() > 0 first

if (text.size() > 0 && 
    text.at(text.size() - 1) != '!' && 
    text.at(text.size() - 1) != '?' && 
    text.at(text.size() - 1) != ':' && 
    text.at(text.size() - 1) != ',' && 
    text.at(text.size() - 1) != ';' && 
    text.at(text.size() - 1) != '=')

or maybe you intended this logic (it's not really clear from your question)

if (text.size() == 0 || 
    (text.at(text.size() - 1) != '!' && 
     text.at(text.size() - 1) != '?' && 
     text.at(text.size() - 1) != ':' && 
     text.at(text.size() - 1) != ',' && 
     text.at(text.size() - 1) != ';' && 
     text.at(text.size() - 1) != '='))

You should also simplify that expression, it's way too complex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM