Title Case a Sentence: Is this a dumb solution?

So i solved it after dealing with a strange bug with my first iteration. Essentially the first element appeared twice: once as an uppercase letter then as a lower case.

the following is my final code:

function titleCase(str) {
  let finalStr = str.toUpperCase().charAt(0)
for (var i = 1, len = str.length; i < len ; i++){

  if (str.charAt(i - 1) == " "){
    finalStr += str.toUpperCase().charAt(i);
  }

  else
     finalStr +=  str.toLowerCase().charAt(i);
}

  return finalStr;
}

console.log(titleCase("I'm a little tea pot"));

next is my buggy code that i have no idea why it is bugging:

function titleCase(str) {
  let finalStr = ""
for (var i = 0, len = str.length; i < len ; i++){
if (i == 0){
 finalStr += str.toUpperCase().charAt(i);
}
  if (str.charAt(i - 1) == " "){
    finalStr += str.toUpperCase().charAt(i);
  }

  else
     finalStr +=  str.toLowerCase().charAt(i);
}

  return finalStr;
}

console.log(titleCase("I'm a little tea pot"));

So two questions:

  1. Is this a suboptimal/not good code to solve a problem like this? The answer said that i should have split it into an Array and used replace. If it is bad code, why is this inferior to the provided solution?

  2. Why did my buggy solution repeat the first character of the string twice?

you have an if statement that execute when i == 0 then you have an if/else, the if execute i’d previous character is a space, and the else all the other times
when i is 0 both that if, and the else of the other chain execute, so two characters are added for this iteration (pythontutor is a useful tool to discover this stuff, it shows execution of code step by step)


your code works, doesn’t it?

that’s good.

with practice, experience, and research, you will find that stuff that needs multiple lines can be obtained with just a single method.
But being able to solve with basic stuff is awesome.

1 Like