在Javascript中创建一波字符串

时间:2019-03-04 12:21:29

标签: javascript arrays

我似乎无法弄清楚如何用Javascript中的字符串产生波浪。

规则:

  1. 输入将始终为小写字符串。
  2. 忽略空格。

预期结果:

wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

wave (" h e y ") => [" H e y ", " h E y ", " h e Y "]

wave ("") => []

据我所知。当前代码将给我答案["hello", "hello", "hello", "hello", "hello"]。我正在考虑使用第二个for循环并以某种方式将每个新字母大写,但是我很困惑。如果答案可以避免在循环O(n^2)中使用循环,我也将不胜感激。由于 BIG O可扩展性

const wave = (str) => {
    if(typeof str === 'string' && str === str.toLowerCase()){
       for (let index = 0; index < str.length; index++) {
        array.push(str);
    }
    for (let index = 0; index < str.length; index++) {
            console.log(array);   
    }
    }else{
        alert(`${str} is either not a string or not lowercase`);
    }
}
wave("hello");

5 个答案:

答案 0 :(得分:8)

您可以采用外循环来访问字符,如果找到了非空格字符,请在此位置创建一个大写字母的新字符串。

<link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
  integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
  crossorigin="anonymous"
/>
function wave(string) {
    var result = [],
        i;

    for (i = 0; i < string.length; i++) {
        if (string[i] === ' ') continue;
        result.push(Array.from(string, (c, j) => i === j ? c.toUpperCase() : c).join(''));
    }
    return result;
}

console.log(wave("hello"));   // ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
console.log(wave(" h e y ")); // [" H e y ", " h E y ", " h e Y "]
console.log(wave(""));        // []

答案 1 :(得分:1)

做到了。但是,如果您的字符串中有空格,它将输出没有任何“波动字母”的字符串(因为还处理了空格):

const wave = (str = '') => {
  return str
    .split('')
    .map((letter, i, arr) => `${arr.slice(0, i)}${letter.toUpperCase()}${arr.slice(i + 1, arr.length)}`.replace(/,/g, ''));
}

console.log(wave('wave'));
console.log(wave('foo bar'));
console.log(wave());

答案 2 :(得分:1)

您可以在for循环中将字符串中的每个字符都设置为大写,并使用前缀和后缀固定字符串追加

var array=[];
const wave = (str) => {
    if(typeof str === 'string' && str === str.toLowerCase()){
       for (let index = 0; index < str.length; index++) {
       if (str[index] === ' ') continue;
       waveChar=str.charAt(index).toUpperCase();
       preStr=str.substring(0,index);
       postStr=str.substring(index,str.length-1);
        array.push(preStr+waveChar+postStr);
    }
    
    }else{
        alert(`${str} is either not a string or not lowercase`);
    }
}
wave("hello");
console.log(array);

答案 3 :(得分:0)

我使用String原型的修改:

用于实现replaceAt。

// Modify prototype
String.prototype.replaceAt=function(index, replacement) {
    return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

function WaveFunction(str) {
 
  var base = str;
  var R = [];
  var n =str.length;
  
  for (var i=0 ; i<n ;i++){
  
   str = base;
   var c=str.charAt(i);
   var res = c.toUpperCase();
   // console.log(res);
   str = str.replaceAt(i, res);
  
   R.push(str);
  }
  return R;
}

var REZ = WaveFunction("hello");

 console.log(REZ);

答案 4 :(得分:0)

我使用传统的js。在今天的浏览器上可享受99%的折扣。

那里的答案很务实。我对字符串使用数组访问;

魔术是“ String.fromCharCode(str.charCodeAt(x)^ 32);”  当我们调用这条线时,请使其始终为逆。

// Also tested UTF-8 non english chars

var index = 0;
var mydata= "helloçφšteti"; 

function wave (str){

 var FINAL = [];
 var newString = "";

 for (var j =0; j < str.length; j++) {
 for (var x =0; x < str.length; x++) { 

   var rez = "";
     if (x == index) {
       rez =  String.fromCharCode(str.charCodeAt(x) ^ 32);
     } else {
       rez =  str[x];
     }
     newString +=  rez ;
  }
  FINAL.push(newString);
  newString = "";
  index++;
 }

 return FINAL;
}

var rezArray = wave(mydata);

console.log(rezArray);

// Just for teory
console.log(Array.from([1, 2, 3], x => console.log(x)));