Problem: " Write a C++ program to create a new string of the characters at indexes 0,1, 4,5, 8,9 … from a given string. "
Solution (not mine):
#include <iostream>
using namespace std;
string test(string str1)
{
string result = "";
for (int i = 0; i < str1.length(); i += 4)
{
int c = i + 2;
int n = 0;
n += c > str1.length() ? 1 : 2;
result += str1.substr(i, n);
}
return result;
}
int main()
{
cout << test("Python") << endl;
cout << test("JavaScript") << endl;
cout << test("HTML") << endl;
return 0;
}
Whenever I cannot understand some code, I would just do every step on paper by hand, until I understand what it actually does.
This time, I can’t really figure out this line:
n += c > str1.length() ? 1 : 2;
I would appreciate if anyone could write this line in a more clear, beginner-friendly manner.
Thank you for your time.
>Solution :
I can’t really figure out this line:
n += c > str1.length() ? 1 : 2;
This uses the conditional operator and checks the condition that whether c is greater than str1.length() and if so then it is as if we’re doing n+=1 while if the condition is not satisfied then it is as if we’re doing n+=2.
Basically the same as:
if(n > str.length())
{
n+=1;
}
else
{
n+=2;
}