Jump to content

Not adding spaces? .PadRight()?

- - - - -

  • Please log in to reply
1 reply to this topic

#1
demo53

demo53

    Newbie

  • Members
  • PipPip
  • 10 posts
            Console.WriteLine("Please enter in a string that you want to change the word 'yes' into no.");

            string usrString = Console.ReadLine().ToLower();

            string[] stringToArray = usrString.Split(' ');

            string newString = "";

            for (int i = 0; i <= stringToArray.Length - 1; i++)

            {

                if (stringToArray[i] == "yes")

                {

                    stringToArray[i] = "no";

                }

                stringToArray[i] = stringToArray[i].PadRight(1);

                newString = stringToArray[i] +newString;

            }

            

            Console.WriteLine("You new string is: \n{0}", newString);

            Console.ReadKey();

I was practicing this exercise in the book I read, and it wants me to write a console application that accepts a string and replaces all occurrences of the string yes with no.
Well with what I used, I got it to work. But my problem is that it won't add a space to each element before I add it to the string. I thought .PadRight(1) would add a space to the end of the current element, assign it to that element and then it would add that element to my string with the space. I know I could just use .replace(), but I wanted to try without using .replace().

#2
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 242 posts
The PadRight/PadLeft add spaces to the string until it is as long as the parameter you supply. Since you supplied a 1, it will pad the string until the length of the string is 1 or greater, which means only the empty string will get 'padded'. You use PadRight/PadLeft to ensure that a string is at least as long as 'x'.

just throw a + " " on the end of your string (and look up StringBuilder).




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users