1. 程式人生 > >Title Case a Sentence-freecodecamp算法題目

Title Case a Sentence-freecodecamp算法題目

fun eve bject obj little glob 合成 for循環 all

Title Case a Sentence(中單詞首字母大寫)

  1. 要求
    • 確保字符串的每個單詞首字母都大寫,其余部分小寫。
    • 像‘the‘和‘of‘這樣的連接符同理。
  2. 思路
    • 將句子小寫化後用.split(" ")將句子分隔成各單詞組成的數組,
    • 再用for循環將數組中每個單詞用.split(‘‘)分隔成各個字母組成的數組,將數組中第一個元素大寫,即首字母大寫後用.join(‘‘)將字母合成單詞
    • 最後將各數組單詞用.join(‘ ‘)合成句子
  3. 代碼
    1.  1 function titleCase(str) {
       2   // 請把你的代碼寫在這裏
       3   var temp1 = str.toLowerCase().split(" ");
      
      4 for (var i =0;i<temp1.length;i++){ 5 temp1[i] = temp1[i].split(‘‘); 6 temp1[i][0]= temp1[i][0].toUpperCase(); 7 temp1[i] = temp1[i].join(‘‘); 8 } 9 str = temp1.join(‘ ‘); 10 return str; 11 } 12 13 titleCase("I‘m a little tea pot");
  4. 相關鏈接
    • https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/split

Title Case a Sentence-freecodecamp算法題目