Home > Back-end >  How to format a string by altering case with spaces with C#
How to format a string by altering case with spaces with C#

Time:03-01

I am trying to solve a problem based on Altering Case but there is a bit issue with that. Assume the given string is:

"What is your name?"

I want to get the output:

"WhAt Is YoUr NaMe?"

After writing this code

    string str = "What is your name?";
    string[] strSplit = str.Split(' ');
    string strNoSpace = string.Empty;
    string newStr = string.Empty;

    for (int i = 0; i < strSplit.Length; i  )
    {
        strNoSpace  = strSplit[i];
        
    }
    for (int i = 0; i < strNoSpace.Length; i  )
    {
        if (i % 2 == 0)
        {
            newStr  = char.ToUpper(strNoSpace[i]);
        }
        else
        {
            newStr  = char.ToLower(strNoSpace[i]);
        }
        
    }
    Console.WriteLine(newStr);

I am getting this:

"WhAtIsYoUrNaMe?"

If I put space, the result is different:

"WhAt iS YoUr nAmA?"

It would be very kind if anyone help me to figure out what I am doing wrong in the code.

CodePudding user response:

You can insert the string into a StringBuilder. Unlike a string, a StringBuilder is mutable and allows each character to be changed. Also, I would not split the string into words, but instead only invert the case when the character is a letter:

string str = "What is your name?";
bool toUpper = true;

var sb = new StringBuilder(str);
for (int i = 0; i < sb.Length; i  ) {
    if (Char.IsLetter(sb[i])) { 
        if (toUpper) {
            sb[i] = Char.ToUpper(sb[i]);
        } else {
            sb[i] = Char.ToLower(sb[i]);
        }
        toUpper = !toUpper; // Invert the case
    }
}
str = sb.ToString();

The test Char.IsLetter excludes white spaces, digits, and punctuation.

Note that this code uses the Boolean flag toUpper instead of relying on the index's divisibility by two which gives a wrong information after a space.

CodePudding user response:

You're very close! You just need to insert the spaces back into the sentence when you combine it again.

for (int i = 0; i < strNoSpace.Length; i  )
{
      if (i % 2 == 0)
      {
          newStr  = char.ToUpper(strNoSpace[i]);
      }
      else
      {
          newStr  = char.ToLower(strNoSpace[i]);
      }
      newStr  = ' '; // <--- this line
}

// And then trim the remaining whitespace
Console.WriteLine(newStr.Trim());

CodePudding user response:

Well, you explicitly remove all the spaces from the string, and your indexing does not take spaces into account. I would suggest something like this instead:

        bool odd = false;
        var sb = new StringBuilder();
        foreach (var c in str)
        {
            if (char.IsWhiteSpace(c))
            {
                sb.Append(c);
                continue;
            }

            sb.Append(odd ? char.ToLower(c) : char.ToUpper(c));
            odd = !odd;
        }

This keeps a separate state if the character should be lower or upper, and skips spaces.

CodePudding user response:

Try like this:

        string str = "What is your name?";
        var arr = str.ToCharArray();
        int k = 0;
        for (int i = 0; i < arr.Length; i  )
        {
            if (arr[i] == ' ')
            {
                continue;
            }

            if (k % 2 == 0)
                arr[i] = char.ToUpper(arr[i]);
            else
                arr[i] = char.ToLower(arr[i]);
            k  ;
        }
        string newStr = new string(arr);

Out put is:

WhAt Is YoUr NaMe?
  •  Tags:  
  • c#
  • Related