为什么字符串中的非空格元素不更改为upperCase

问题描述 投票:0回答:5

我想编写一个函数,以将偶数索引处的字符串中的字符更改为大写。我不希望我的程序将空格算作偶数索引,即使它落在偶数索引上也是如此。

例如:'这是一个测试'=>'这是一个目标'

我本来有这种解决方案,但是在计算偶数索引时我无法使其忽略空格字符。

function toWeirdCase(string) {

return string.split("").map((x,i) => i%2=== 0 && x!== " " ? x.toUpperCase() : x).join("")

}

这是我的第二次尝试,我不知道为什么字符串元素实际上没有变为大写。任何帮助,将不胜感激。它只是返回原始字符串。

function toWeirdCase(string) {
  let indexCount = 0;
  let isSpace = false;

  for (let i = 0; i < string.length; i++) {
    if (string[i] === " ") {
      isSpace = true;
    }
    if (indexCount % 2 === 0 && !isSpace) {
      string[indexCount] = string[indexCount].toUpperCase();
    }
    indexCount++;
    isSpace = false;
  }

  return string;
}
javascript algorithm
5个回答
0
投票

function toWeirdCase(string) { var index = 0; return Array.from(string, (x, i) => { if (/[^a-z]/.test(x)) index = 0; return ++index % 2 === 0 ? x.toUpperCase() : x; }).join(""); } console.log(toWeirdCase('This is a test')); // 'ThIs Is A TeSt'

0
投票

function toWeirdCase(sentence) { return sentence .split(' ') .map(word => word .split('') .map((c, i) => (i % 2 === 0) ? c.toUpperCase() : c) .join('')).join(' '); }

0
投票
let test = 'This is a test'; test = toWeirdCase(test); //Here you assign the result

这是一个忽略计数中空格的示例解决方案

 

function toWeirdCase(string) { let count = 0; return string.split("").map((x) => { if(x !== " ") count++; if(count%2 === 0) return x.toUpperCase(); else return x; }).join("") } let test = 'This is a test'; test = toWeirdCase(test); console.log(test); //THiS iS a TeSt

0
投票
function toWeirdCase(string) { let spaceCount = 0; // Personal preference: I like the reduce fn for this, but a similar thing could be achieved with map string.split('').reduce((value, letter, index) => { if (letter === ' ') spaceCount++; return value += ((index - spaceCount) % 2) ? letter : letter.toUpperCase(); },'') }`

如果对空间计数进行累加的索引除以2后得到余数,则返回leter。


0
投票

const str = "this is a test"; function toWeirdCase(str) { return str.split(" ").map(word => ( [...word].map((c, i) => i % 2 === 0 ? c.toUpperCase() : c.toLowerCase())).join("")).join(" "); } console.log(toWeirdCase(str));
© www.soinside.com 2019 - 2024. All rights reserved.