简体   繁体   中英

While loop checking for capital letters in string

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 eg 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 decryptMessage(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 /(.(?=[AZ]))/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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM