In general, you don't want to fit your solution in to one line, so lets break this up in to the indivdual parts so we can see why it doesn't work, what we want and how we would do that.
What it is at the moment
string s = "word";
string p1 = s + s[s.size() - 1] == 's' ? "" : "s";
means:
if(s + s[s.size() - 1] == 's')
{
p1 = "";
}
else
{
p1 = "s";
}
What's wrong
It is now clear why this won't work, firstly we are comaring a string (s + s[s.size() -1]
) to a character s
Also, looking at the result, I suspect that isn't what you want.
The Fix
Instead we want to append an 's' if the last character is not an s. So in long form:
if(s[s.size() - 1] == 's') // compare the last character
{
p1 = s + ""; // equivalently = s but for clarity in the next step we'll write it like this
}
else
{
p1 = s + "s"; // append the s
}
So now we can condense this back down, adding in brackets to get the desired behaviour
string p1 = s + (s[s.size() - 1] == 's' ? "" : "s");
We append something to s
, where the something is determined by the last character of s