Capitalize first letter in every word in a string.

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

36 Replies - 12088 Views - Last Post: 10 February 2018 - 09:58 PM Rate Topic: -----

#1 HaDaEx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 07-January 14

Capitalize first letter in every word in a string.

Posted 07 January 2014 - 04:35 AM

Hey, I have what I consider to be basic C# experience, and no experience in any other languages. At high school we've been learning at a really slow pace, and I really wanted to advance more quickly so in this holiday break I read up the while loop, methods, functions, classes and strings from my textbook, in that order. I understand and can use every one of those, but I have a difficulty with string methods for some reason. I tried solving a question from my book, which requires me to capitalize the first letter of every word in a string. I kept trying for maybe two hours yesterday, re-reading the string chapter to see if I'm forgetting a certain method or if something similar was discussed in the examples but I didn't find anything. I also googled it, and found a few answers, none of which I understood. They mostly had keywords or methods I wasn't familiar with.
Anyway, here's where I am so far.
class Program
    {
        static string UpperCase(string s)
        {
            int place; string b, st1, st2,st3; char letter;
            for (int i = 0; i <= s.Length - 1; i++)
            {

                
                if (i == 0)
                {
                    letter = s[0];
                    b = letter.ToString(); b = b.ToUpper(); s = s.Replace(s[0], b[0]);
                }
                else
                {
                    st1 = s.Substring(0, i);
                    st2 = s.Substring(i);
                    place = st2.IndexOf(" ") + 1;
                    letter = st2[place];
                    b = letter.ToString(); b = b.ToUpper(); st3=st2.Replace(st2[place], b[0]);
                    s = st1 + st3;    
                }
                
            }
            Console.WriteLine("The string is: ");
            Console.WriteLine(s);
            return s;
        }
        static void Main(string[] args)
        {
            string s;
            Console.Write("Enter string: ");
            s = Console.ReadLine();
            UpperCase(s);

        }
    }


The code compiles without any errors, but when I enter a string it capitalizes correctly for the first two words and then it starts capitalizing letters in the middle of the words. I should probably just delete it and start over as I'm pretty sure it's either something really simple or really stupid. It was written at midnight, after all.

So, I don't want you to give me the whole code, and I know you won't, but some pointers and tips will be well appreciated. Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Capitalize first letter in every word in a string.

#2 Charles:)   User is offline

  • D.I.C Regular

Reputation: 149
  • View blog
  • Posts: 359
  • Joined: 26-November 09

Re: Capitalize first letter in every word in a string.

Posted 07 January 2014 - 06:28 AM

You need to do something like this (pseudo-code):

function Capitalize(string toCapitalize)

    bool prevCharWasSeparator = true

    for each char in toCapitalize
        if isSeparator(char) then
            prevCharWasSeparator = true
        else
            if prevCharWasSeparator then
                makeUppercase(char)
            endif
            prevCharWasSeparator = false
        endif
    next

end function

function isSeparator(char c)
    if c is whitespace, full stop, comma etc. then
        return true
    else
        return false
    end if
end function



Make sure that the isSeparator function doesn't cause letters after apostrophes to be capitalized. There are a few corner cases like that to consider, but that's left to you as an exercise to improve the algorithm.

This post has been edited by Charles:): 07 January 2014 - 06:30 AM

Was This Post Helpful? 2
  • +
  • -

#3 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6536
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Capitalize first letter in every word in a string.

Posted 07 January 2014 - 06:32 AM

Charles shows a good method. Just to show that there is generally more than one way to do anything in code here is another:
If you split the sentence on the space character (string.split()) you get an array of strings (the words)
You can then capitalize each one.
Then reassemble the array back into a sentence.
Was This Post Helpful? 1
  • +
  • -

#4 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6833
  • View blog
  • Posts: 28,342
  • Joined: 12-December 12

Re: Capitalize first letter in every word in a string.

Posted 07 January 2014 - 06:44 AM

There are more sophisticated, and succinct, ways to do this, but the essential problem with your code is that you are working with, and over-writing, the original string s.

You need to create a temporary string
Loop through the passed string, appending (concatenating) its characters to your temp-string
If it is the first character, uppercase and append it
If it is a space append it, but set a flag (a boolean) to true
Else if it is not a space, then
    Check the flag. If it's true append the uppercase (current) character
        and set the flag to false
    Otherwise append the lowercase (current) character
Return the temporary string.

Added: A step can be save by setting the flag initially to true.

Charles' code is similar to this.

This post has been edited by andrewsw: 07 January 2014 - 10:51 AM

Was This Post Helpful? 1
  • +
  • -

#5 HaDaEx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 07-January 14

Re: Capitalize first letter in every word in a string.

Posted 07 January 2014 - 08:12 AM

Thanks for the fast replies everyone! I'll try it out soon and get back to you.
Was This Post Helpful? 0
  • +
  • -

#6 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Capitalize first letter in every word in a string.

Posted 07 January 2014 - 08:18 AM

I suggest following the advice in this thread, and try it on your own. Once you figure it out, then you can leave it behind and do it the simple way:

http://msdn.microsof...(v=vs.110).aspx
Was This Post Helpful? 1
  • +
  • -

#7 HaDaEx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 07-January 14

Re: Capitalize first letter in every word in a string.

Posted 07 January 2014 - 10:49 AM

I think I'm just going to drop this question for now... I tried to follow your instructions but nothing worked.

Right now I'm getting this error:

 Enter string: fgdsga
0F
Unhandled Exception: System.FormatException: Index (zero based) must be greater
than or equal to zero and less than the size of the argument list.
   at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String fo
rmat, Object[] args)
   at System.String.Format(IFormatProvider provider, String format, Object[] arg
s)
   at System.IO.TextWriter.WriteLine(String format, Object arg0)
   at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0)
   at System.Console.WriteLine(String format, Object arg0)
   at ConsoleApplication21.Program.MakeUpperCase(String s) in c:\Users\2012\Docu
ments\Visual Studio 2012\Projects\ConsoleApplication21\ConsoleApplication21\Prog
ram.cs:line 84
   at ConsoleApplication21.Program.Main(String[] args) in c:\Users\2012\Document
s\Visual Studio 2012\Projects\ConsoleApplication21\ConsoleApplication21\Program.
cs:line 99
Press any key to continue . . .



    class Program
    {
        static bool isSeperator(char c)
        {
            if ((c == ' ') || (c == '.') || (c == ','))
                return true;
            else return false;

        }
        static string MakeUpperCase(string s)
        {
            bool prevCharSeperator = true; char c; string temp = "", b, st1 = "", st2 = "";
           /* for (int i = 0; i < s.Length - 1; i++)
            {
               
                c = s[i];
                if (isSeperator(s[i]))
                {
                    prevCharSeperator = true;
                    Console.WriteLine("{0}. temp = {1}", i, temp);
                    temp=temp+s[i];
                }
                else if (prevCharSeperator)
                {

                    temp = temp + s[i];
                    b = c.ToString(); st2 = b.ToUpper();
                    temp = temp + st2;
                    prevCharSeperator = false;
                    
                    Console.WriteLine("{0}. temp = {1}", i, temp);
                }
                else
                {
                    if (i == 0)
                    {
                        c = s[0];
                        b = c.ToString(); st1 = b.ToUpper();
                        temp = st1;
                        Console.WriteLine("{0}. temp = {1}", i, temp);

                    }
                    b = c.ToString();
                    temp = temp + b;
                    Console.WriteLine("{0}. temp = {1}", i, temp);
                    
                }


            }*/

            //foreach (char y in s) I tried a foreach loop but it didn't work and I'm not familiar with it
            for (int i=0;i<=s.Length-1;i++)

            {
                if (i == 0)
                {
                    c = s[0];
                    c = char.ToUpper(c);
                    temp = c.ToString();
                        Console.Write(i+temp);
                }
                else
                {
                    if (isSeperator(s[i]))  //if (isSeperator(y)......you get the idea.
                    {
                        prevCharSeperator = true;
                        temp = temp + s[i];
                    }
                    else if (prevCharSeperator)
                    {

                        Char.ToUpper(s[i]);
                        prevCharSeperator = false;
                        temp = temp + s[i];
                        Console.WriteLine(" temp = {1}", temp);
                    }
                }
            }

            
            
            
            return temp;
        }
        static void Main(string[] args)
        {
            string s;
            Console.Write("Enter string: ");
            s = Console.ReadLine();
           s= MakeUpperCase(s);
            Console.WriteLine(s);
        }



I put what I tried in a comment.
I think I need to leave strings alone for a while and come back to them later. I mean it seems simple but I can't do it for some reason... This is the first time I got stuck on something =/ Bummer.

I haven't tried the split method yet but I think that's enough for today. Thanks everyone!
Was This Post Helpful? 0
  • +
  • -

#8 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6833
  • View blog
  • Posts: 28,342
  • Joined: 12-December 12

Re: Capitalize first letter in every word in a string.

Posted 07 January 2014 - 11:22 AM

I don't like to provide code but it seems a shame when you are close.

I appreciate the benefit in sometimes moving on to other topics. When you return to this topic you might study the following code. I am assuming this is not an assignment!

Spoiler

But you should also compare it to your own code, to discover where you were going wrong. There is a debugging tutorial linked in my signature below.

An additional task would be to collapse consecutive spaces to a single space.

This post has been edited by andrewsw: 07 January 2014 - 11:26 AM

Was This Post Helpful? 1
  • +
  • -

#9 HaDaEx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 07-January 14

Re: Capitalize first letter in every word in a string.

Posted 08 January 2014 - 06:02 AM

So close and yet so far... To be honest, as soon as I saw your reply I couldn't wait, but I was on a mobile device so I couldn't view the code. As soon as I woke up today I checked your code and compared it to mine.
First thing I noticed was this:
temp += s[i].ToString().ToLower();
I didn't know you could use two methods in one statement.
I also haven't used chars much in class and I assumed that using the + would convert it to string since it wasn't showing an error.
And setting the prevSeperator to true made it so that it capitalized the first letter without having to write a few lines of code especially for it. I had it set to true but also had some lines ( if (i==0) ... ) which cause the first word to have a duplicated first letter.

Thanks again. It all seems so simple now haha.

Oh and don't worry, it wasn't an assignment. My teacher teaches at a slow pace and gives the impression of being lazy, but he does try to give us homework. We had exams for a couple of weeks and then the holidays, so my classmates convinced him not to give us any.

I'll be coming back to this forum if I have anymore problems. Thanks again!

This post has been edited by andrewsw: 08 January 2014 - 06:30 AM
Reason for edit:: Removed previous quote

Was This Post Helpful? 0
  • +
  • -

#10 Charles:)   User is offline

  • D.I.C Regular

Reputation: 149
  • View blog
  • Posts: 359
  • Joined: 26-November 09

Re: Capitalize first letter in every word in a string.

Posted 08 January 2014 - 06:03 AM

You need to look at the information in the error message to see what's gone wrong.

Have a look at this line:

Console.WriteLine(" temp = {1}", temp); 


Compare it to your other Console.WriteLine calls and read the MSDN documentation to see the correct way to call this function.
Was This Post Helpful? 1
  • +
  • -

#11 HaDaEx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 07-January 14

Re: Capitalize first letter in every word in a string.

Posted 08 January 2014 - 06:09 AM

Yes I looked at the line in the error. As soon as I deleted it it started working again. At first I thought it had something to do with it being a string but then I remembered that it was possible to use the {} with strings. Earlier I had another sentence/variable in the Console.WriteLine and when I deleted it I forgot to update the {1} to a {0}. I actually didn't know WHY it was giving an error until you mentioned it just now actually and I really looked at it. Guess I'll have to be more careful in the future. It was really frustrating.

As a matter of fact I thought error was about me using s[i] in the loop so I didn't look there, but then I enabled line numbers and checked the code.
Was This Post Helpful? 0
  • +
  • -

#12 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6833
  • View blog
  • Posts: 28,342
  • Joined: 12-December 12

Re: Capitalize first letter in every word in a string.

Posted 08 January 2014 - 07:13 AM

OP said:

I assumed that using the + would convert it to string since it wasn't showing an error.

temp += s[i];

This works and will concatenate a character to a string. But the ToLower() method applies to a string, not a character, so I first had to convert it to a string:

temp += s[i].ToString().ToLower();

method.method.method is called method chaining, for obvious reasons ;)
Was This Post Helpful? 1
  • +
  • -

#13 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Capitalize first letter in every word in a string.

Posted 08 January 2014 - 08:21 AM

View PostHaDaEx, on 08 January 2014 - 07:02 AM, said:

temp += s[i].ToString().ToLower();
I didn't know you could use two methods in one statement.


Just to clarify what happens here, expressions are evaluated from left-to-right (assuming no other precedence from order of operations), and as each part of the expression is evaluated, it's replaced with its result. So, in this case:

s[i].ToString().ToLower()

is broken up like this:

((s[(i)]).ToString()).ToLower()

And evaluated piecewise. Let's assume that i == 0 and s[0] == 'A'.

1. s[i].ToString().ToLower()
2. s[0].ToString().ToLower()
3. 'A'.ToString().ToLower()
4. "A".ToLower()
5. "a"



And that's how method chains are evaluated.
Was This Post Helpful? 2
  • +
  • -

#14 Momerath   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1021
  • View blog
  • Posts: 2,463
  • Joined: 04-October 09

Re: Capitalize first letter in every word in a string.

Posted 08 January 2014 - 10:34 AM

Just adding something because it's one of my Pet Peeves:
for (int i = 0; i <= s.Length - 1; i++)

This causes a method call then a math call each time it checks for the loop conditions.
for (int i = 0; i < s.Length; i++)

Just the method call, no need for the math, does the exact same range.
Was This Post Helpful? 0
  • +
  • -

#15 HaDaEx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 07-January 14

Re: Capitalize first letter in every word in a string.

Posted 08 January 2014 - 11:12 AM

Method chaining seems useful. I'll keep it in mind.
I had trouble with using the ToUpper() and MakeUpperCase() methods because I kept trying to use them with chars xD
I understand everything now though :w00t:
I'll try to do a few more exercises now. Tomorrow however I go back to school from the break so I might not be able to dedicate much time to programming AND gaming. I'll probably have to choose one or the other each day. Oh well.
Thanks again guys!



View PostMomerath, on 08 January 2014 - 10:34 AM, said:

Just adding something because it's one of my Pet Peeves:
for (int i = 0; i <= s.Length - 1; i++)

This causes a method call then a math call each time it checks for the loop conditions.
for (int i = 0; i < s.Length; i++)

Just the method call, no need for the math, does the exact same range.


I thought that I wasn't supposed to use the length of a string in a loop? Or was that for arrays?
Um nevermind I think I saw it in an example somewhere where it wasn't necessary to check the last letter because there was no way it could achieve the result needed. I'll keep that in mind as well. :bigsmile:
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3