Titania Lo
Titania Lo

Reputation: 65

Splitting the letters based on position of letter

I am trying to spilt a string word into two strings based on the letter position. The two strings are even and odd. I manage to read the string and used a for loop but the conditional operator is not working and give me the error below. What did I do wrong?

Example: The string word is pole Even position string - oe Odd position string - pl

Error

Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
string word = Console.ReadLine(); 
for(int i = 0; i < word.Length; i++)
{
     string even = "";
     string odd = ""; 
           
     ((i % 2 == 0) ? even += word[i]: odd += word[i]);
}

Upvotes: 1

Views: 77

Answers (4)

SomeBody
SomeBody

Reputation: 8743

You can also use LINQ to get the expected result:

string word = Console.ReadLine(); 
string even = string.Concat(word.Where((c,i) => i % 2 == 0));
string odd = string.Concat(word.Where((c,i) => i % 2 == 1));

Online demo: https://dotnetfiddle.net/ePWHnp

Upvotes: 1

Anu Viswan
Anu Viswan

Reputation: 18153

You could use the discard operator as the following.

string word = Console.ReadLine(); 
string even = "";
string odd = ""; 
for(int i = 0; i < word.Length; i++)
{
      
   var _ = ((i % 2 == 0) ? even += word[i]: odd += word[i]);
}

Couple of points to note here.

  • You need to declare the odd,even variables outside the loop, otherwise it would be recreated for each iteration of loop
  • Remember the string is immutable.You could also consider the StringBuilder class.

Upvotes: 2

JohnG
JohnG

Reputation: 9479

I am not that familiar with the ? operator, however, in my research, it appears it wants something like below…

((i % 2 == 0) ? ref even : ref odd) += word[i];

Unfortunately, even with this change, the even and odd variables are getting “reset” to empty with each iteration of the for loop with…

string even = "";
string odd = "";

If the goal is to concatenate the values, you do NOT want to create new even and odd variables with each iteration. So you should move those declarations “outside” the for loop. Something like…

string word = Console.ReadLine();
string even = "";
string odd = "";
for (int i = 0; i < word.Length; i++) {
  ((i % 2 == 0) ? ref even : ref odd) += word[i];
}

Upvotes: 1

Dzianis Karpuk
Dzianis Karpuk

Reputation: 146

You use conditional operator to assign values inside of it. It is not allowed. The correct for-loop is:

        for (int i = 0; i < word.Length; i++)
        {
            if (i % 2 == 0)
            {
                even += word[i];
            }
            else
            {
                odd += word[i];
            };
        }

Upvotes: 1

Related Questions