开发者

While loop checking for capital letters in string

开发者 https://www.devze.com 2023-03-07 14:55 出处:网络
I have a function which checks if a given character is capital letter and returns true of false value:

I have a function which checks if a given character is capital letter and returns true of false value:

function isUpperCase(aCharacter)
{
    return (aCharacter >= 'A') && (aCharacter <= 'Z');
}

Now I have a string of characters e.g. ThksAbcdEvat.

I want to write a function which checks every character in a string and when it encounters a capital letter is will execute function decryptW but only on a block of letters until next capital letter.

Function decryptW works fine on single words. So what im looking for is execution of function 'decryptW' on 'Thks' 'Abcd' 'Evat' and return 3 words as a result. all i have at the moment is:

function decr开发者_如何转开发yptMessage(cipherText, indexCharacter, plainAlphabet, cipherAlphabet)
{
    for (var count = 0, count < cipherText.length; count++)
    {
        while (isUpperCase(cipherText.charAt(count))
        {
            if (count - lastCapital > 1)
            {
                decryptWord(cipherText, indexCharacter, plainAlphabet, cipherAlphabet);
                lastCapital = count;
            }
        }
    }
}

Can you tell me if I'm even close to what I want to achieve? Any help would be much appreciated.


Probably regular expression can help you

var re = /[A-Z][a-z]*/;
var s = 'ThksAbcdEvat';
s.replace(re, function(c){
    //do something with c
    return c;
});


For what you describe (if I understood right) using String.replace/split will do the job of splitting up the string on its capitals:

'ThksAbcdEvat'.replace(/(.(?=[A-Z]))/g,'$1,').split(',');
 //=> Thks,Abcd,Evat

Where /(.(?=[A-Z]))/g means: find any character followed by a capital A to Z, and the replacement ('$1,') means: add a ',' (comma) to the found character(s).

After that you can run a loop to apply decryptWord to every word in the array (/g means: global, i.e. do that for the whole string). So your whole decryptMessage function could look like:

function decryptMessage(cipherText /*,... other params*/ ){
  var captalWords = cipherText.replace(/(.(?=[A-Z]))/g,'$1,').split(',');
  for (var i=0;i<capitalWords.length;i++){
   decryptWord(captalWords[i] /*,... other params*/ );
  }
}

I'd say, no real need for complex while loops etc. here.

0

精彩评论

暂无评论...
验证码 换一张
取 消