WeIrD StRiNg CaSe

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WeIrD StRiNg CaSe相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

使用 CASE [String] 时 SELECT CASE 语句的奇怪行为

在这个 spark 代码片段中 ordering.by 是啥意思?

根据字符串名称而不是列表视图项位置替换片段并启动活动

.NET如何把string转换成short

ruby weird.rb

cf299C Weird Game