简体   繁体   English

在保持顺序的同时将字符串大写字母移到前面(JavaScript)

[英]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.我正在使用编码 class,我们被要求制作一段代码,要求输入一个短语,并在控制台中返回该短语,并将大写字母移到前面,但顺序仍然相同。 Then print to the console this reordered phrase.然后将这个重新排序的短语打印到控制台。 (We aren't allowed to use arrays) For example: Inputting "HeLLoTherE" would return "HLLTEeoher" (我们不允许使用数组)例如:输入"HeLLoTherE"将返回"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?我怎样才能使代码 select 这些大写字母移动到前面呢? using.toUpperCase()?使用.toUpperCase()? How can i make that select the letter and move it in front of the rest?我怎样才能使 select 成为字母并将其移动到 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.好吧,你不能使用 arrays,这有点困难,但是你仍然可以做一些事情。

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.虽然我使用的是 for 循环,但我实际上并没有使用 arrays。由于字符串允许使用[]运算符,因此您可以使用索引 select 字符串的每个字符并检查它是小写还是大写。

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.另外,你说你需要保持大写字母的顺序,所以你不能只做newStr = upper + newStr ,因为它会恢复原来的顺序。 So, I used the string.prototype.substring() to insert the uppercase character where it should be.因此,我使用string.prototype.substring()将大写字符插入到应该插入的位置。

 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.然后,您可以通过组合条件来合并 2 个循环。

 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.遵循使用for...of循环迭代输入的解决方案。 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.然后go回去找其他的字符,在最后加上。 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.真正困难的部分是想出一种方法来检测所有 Unicode 中的“大写”字母。某些语言(好吧,正字法)根本没有这个概念。 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. JavaScript 有越来越多和不太方便的方法来处理这个问题,但我怀疑 OP 到目前为止可用的课堂材料,考虑到原始问题的性质,这种正则表达式技巧可能不适合作为答案。

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('')
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将所有大写字母移动到字符串的开头? - How to move all capital letters to the beginning of the string? While循环检查字符串中的大写字母 - While loop checking for capital letters in string JavaScript:如何在保持单词、空格和标点符号的原始顺序的同时反转每个单词中的字母? - JavaScript: How to reverse letters in each word while maintaining the original order of words, spaces and punctuation? 如何在不使用任何正则表达式/内置 function 如 split、join、indexOf 等的情况下将大写字母移动到前面 - How to move capital letters in front without using any regular expression/ built in function such as split,join,indexOf etc Javascript:在一个字符串中,替换大写字母和它后面的所有字母 - Javascript: in a string, replace the capital letter and all letters following it JavaScript使用正则表达式按大写字母拆分字符串,除非一起使用 - JavaScript Using Regex to split string by capital letters except when together JavaScript 反转字符串中每个单词的字母顺序 - JavaScript reverse the order of letters for each word in a string 确定字符串中的所有字母是否都按字母顺序排列 - Determine if all letters in a string are in alphabetical order JavaScript JavaScript的大写字母排序方法处理 - JavaScript's sort method handling of capital letters Javascript正则表达式查找所有大写字母 - Javascript regex find all capital letters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM