Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I write this line of code in a more readable manner?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading