首页 > 其他 > 详细

WeIrD StRiNg CaSe

时间:2016-11-17 13:33:25      阅读:160      评论:0      收藏:0      [点我收藏+]

Description:

Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.

The passed in string will only consist of alphabetical characters and spaces(‘ ‘). Spaces will only be present if there are multiple words. Words will be separated by a single space(‘ ‘).

Examples:

toWeirdCase( "String" );//=> returns "StRiNg"
toWeirdCase( "Weird string case" );//=> returns "WeIrD StRiNg CaSe"

解题:

function write(string){
var nstr=‘‘;
var result=‘‘;
var n=‘‘;
    string.split(‘ ‘).forEach(function(items,index){
           items.split(‘‘).forEach(function(item ,index){
              nstr +=(index % 2 == 0 ? item.toUpperCase() : item.toLowerCase());
          });
       result += nstr + ‘ ‘;
     })
   console.log(result);
    result.split(‘ ‘).forEach(function(item,index){    
              console.log(item+‘,‘+result.split(‘ ‘)[index-1]);      
              n+= item.replace(result.split(‘ ‘)[index-1],‘ ‘);
   })
     return n;
}
write(‘This is a test‘); 

大神解法:

function toWeirdCase(string){
  return string.split(‘ ‘).map(function(word){
    return word.split(‘‘).map(function(letter, index){
      return index % 2 == 0 ? letter.toUpperCase() : letter.toLowerCase()
    }).join(‘‘);
  }).join(‘ ‘);
}

少了两层循环 ,我还是js函数用的少

function toWeirdCase(string){
  return string.replace(/(\w{1,2})/g,(m)=>m[0].toUpperCase()+m.slice(1))
}

这....

function toWeirdCase(string) {
  var i = 0;
  return [].map.call(string.toLowerCase(), function(char) {
    if (char == " ") { i = -1; }
    return i++ % 2 ? char : char.toUpperCase();
  }).join(‘‘);
}
function toWeirdCase(string){
  return string.split(/ /g).map(function (word) { return word.split(‘‘).map(function (c, i) { return i % 2 ? c.toLowerCase() : c.toUpperCase(); }).join(‘‘) }).join(‘ ‘);
}

都能明白,也没啥高深的东西 ,方法多解要多练

WeIrD StRiNg CaSe

原文:http://www.cnblogs.com/shaoxiablogs/p/6073308.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!