0
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Globalization;

    namespace Project_Scorps_1
    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Convert_Click(object sender, EventArgs e)
        {
            string s = textBox1.Text;
            char [] c = new char [s.Length];
            for (int i = 0; i < s.Length; i++)
            {
                if (i % 2 == 0)
                {
                    (s[i].ToString()).ToUpper(CultureInfo.InvariantCulture);
                }

                if (i % 2 != 0)
                {
                    (s[i].ToString()).ToLower();
                }
            }

            textBox2.Text = s;
        }
    }
}

This is the code I have so far. textBox1 is the text box you enter your sentance in, and textbox2 is the box that contains the output.

It gives me output that is the same sentence I inputted!

Scorps
  • 405
  • 2
  • 7
  • 9

3 Answers3

3

This is because strings are immutable. The value is said to be immutable because it can *not* be modified once it has been created by appending, removing, replacing, or inserting characters. What you can do however, is use the existing string (or character in the string) to build a new string:

string result = string.Empty;
string s = textBox1.Text;
char[] c = new char[s.Length];
for (int i = 0; i < s.Length; i++)
{
    if (i % 2 == 0)
    {
        result += (s[i].ToString()).ToUpper(CultureInfo.InvariantCulture);
    }

    if (i % 2 != 0)
    {
        result += (s[i].ToString()).ToLower();
    }
}

textBox2.Text = result;

Creating a new string every time you append a character can be a fairly expensive operation. If your inputs are considerably long you should consider using a StringBuilder. You can read more about the StringBuilder here.

Also, you don't need to calculate the modulus twice, you can just use an if..else instead.

Community
  • 1
  • 1
User 12345678
  • 7,714
  • 2
  • 28
  • 46
1

Strings are immutable - you aren't changing them. You'll need to have a separate variable to hold your result:

string result = "";
for (int i = 0; i < s.Length; i++)
{
    if (i % 2 == 0)
    {
        result += (s[i].ToString()).ToUpper(CultureInfo.InvariantCulture);
    }

    if (i % 2 != 0)
    {
        result += (s[i].ToString()).ToLower();
    }
}

textBox2.Text = result;
Femaref
  • 60,705
  • 7
  • 138
  • 176
0

It could be shorter with the help of Linq

string s = "This  Kind Of Text";

var newstr = String.Join("", s.Select((c, i) => i % 2 == 0 
                                 ? char.ToLower(c, CultureInfo.InvariantCulture) 
                                 : char.ToUpper(c, CultureInfo.InvariantCulture)));
I4V
  • 34,891
  • 6
  • 67
  • 79