简体   繁体   中英

Move string capital letters to front while maintaining the order (JavaScript)

This is my first post so I hope im doing this correctly.

I am taking a coding class and we were asked to make a piece of code that will ask for the input of a phrase, and will return in the console that phrase with the capital letters moved to the front, but still in the same order. Then print to the console this reordered phrase. (We aren't allowed to use arrays) For example: Inputting "HeLLoTherE" would return "HLLTEeoher"

However the problem is im having issues understanding how to write this code. How can I make the code select these capital letters and move them to the front? using.toUpperCase()? How can i make that select the letter and move it in front of the rest? If someone could show me an example of how this is done and explain it a little i would greatly appreciate it:)

Well, you are not able to use arrays, which makes it a little bit difficult, however you can still do sommething.

Although I'm using a for loop, I'm not actually using arrays. Since strings allows the [] operator, you can use an index to select each character of the string and check if it's lowercase or uppercase.

In addition, you said you need to mantain the order of uppercase letters, so you couldn't just do newStr = upper + newStr , because it would revert the original order. So, I used the string.prototype.substring() to insert the uppercase character where it should be.

 const str = "HeLLoTherE"; const moveUpperToFront = (target) => { // Strings are immutable in js, so you cannot move one character // to the front without using a new string. let newStr = ""; // Number of uppercase letters that appeared. // It's necessary because you need to mantain the original order let upperNumber = 0; // Iterate each character from beginning for (let i = 0; i < str.length; ++i) { // Is there an uppercase letter? if (str[i].charCodeAt() >= 65 && str[i].charCodeAt() <= 90) { newStr = newStr.substring(0, upperNumber) + str[i] + newStr.substring(upperNumber, newStr.length); ++upperNumber; } // No uppercase letter? else newStr += str[i]; } return newStr; }; console.log(moveUpperToFront(str));

You might just start with a the most straight forward algorithm to get something working.

 let value = "HeLLoTherE"; let result = ""; for (let char of value) { if (char >= "A" && char <= "Z") { result += char; } } for (let char of value) { if (char >= "a" && char <= "z") { result += char; } } console.log(result);

You could then consolidate the 2 loops by combining the conditions.

 let value = "HeLLoTherE"; let upper = ""; let lower = ""; for (let char of value) { if (char >= "A" && char <= "Z") { upper += char; } else if (char >= "a" && char <= "z") { lower += char; } } console.log(upper + lower);

Another way of solving this would be to use regex.

 var value = "HeLLoTherE"; var upper = value.replace(/[^AZ]*/g, ""); var lower = value.replace(/[^az]*/g, ""); console.log(upper + lower);

This answer tries to achieve the desired objective without using "arrays". It does use back-ticks, but that can be replaced with a simple string-concatenation if required.

Code Snippet

 // move upper-case letters while // keeping relative order same const capsWithOrder = str => { // initialize result variables let capsOnly = "", restAll = ""; // iterate over the given string input for (let i = 0; i < str.length; i++) { // if character at index "i" is upper-case // then, concatenate character to "capsOnly" // else, concatenate to "restAll" if (str[i] === str[i].toUpperCase()) capsOnly += str[i]; else restAll += str[i]; }; // after iterating over all characters in string-input // return capsOnly concatenated with restAll return `${capsOnly}${restAll}`; }; console.log(capsWithOrder("HeLLoTherE"));

Explanation

Inline comments added in the snippet above.

Following a solution which uses a for...of loop to iterate the input. It splits the input into capital and lowercase literals and then merges back together:

const exampleLiteral = 'HeLLoTherE';

const isUppercase = (literal) => literal === literal.toUpperCase() && literal !== literal.toLowerCase();

const prefixCapitalLetters = (literal) => {
    let capitalLetters = '';
    let lowerLetters = '';
    for (let letter of literal) {
        if(isUppercase(letter)) {
            capitalLetters = capitalLetters.concat(letter);
            continue;
        }
        lowerLetters = lowerLetters.concat(letter);
    };
    return capitalLetters+lowerLetters;
}

console.log(prefixCapitalLetters(exampleLiteral));

This is really not a very hard problem:

 function rearrange(str) { let result = ""; for (let c of str) if (c >= 'A' && c <= 'Z') result += c; for (let c of str) if (c < 'A' || c > 'Z') result += c; return result; } console.log(rearrange("Hello World, It Is A Beautiful Morning;"));

Find the upper-case characters, and add them to a result string. Then go back and find the other characters, and add them at the end. By looping through without any sorting, just simple iteration from start to finish, the order is preserved (other than the upper-case stuff).

The truly hard part of this would be coming up with a way to detect "upper-case" letters across all of Unicode. Some languages (well, orthographies) don't have the concept at all. JavaScript has ways that are more and less convenient to deal with that, but I suspect for the classroom material the OP has available so far, given the nature of the original question, such regex trickery would probably be inappropriate for an answer.

Something like this

 const string1 = 'HeLLoTherE' const transform = string => { const lower = string.split('').filter(c => c.charCodeAt() > 'a'.charCodeAt()) const upper = string.split('').filter(c => c.charCodeAt() < 'Z'.charCodeAt()) return [...upper, ...lower].join('') } console.log(transform(string1))

I think that must be work.

const sort = [
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
    'abcdefghijklmnopqrstuvwxyz'.split('')
]

function listByValue(string) {
    string = [...string];
    let ret = [];
    for (let i in sort) 
        ret = [...ret,...string.filter(e=>sort[i].includes(e))];
    return ret.join('')
}

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