-
Notifications
You must be signed in to change notification settings - Fork 3.3k
第 69 题: 如何把一个字符串的大小写取反(大写变小写小写变大写),例如 ’AbC' 变成 'aBc' 。 #116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
有没有想到用ascii码的? const STEP = 'a'.charCodeAt() - 'A'.charCodeAt();
function transCase(char) {
const asciiCode = char.charCodeAt();
const resultCode = asciiCode < 'a'.charCodeAt() ? asciiCode + STEP : asciiCode - STEP;
return String.fromCharCode(resultCode);
}
function transStr(str) {
const charArr = str.split('');
return charArr.map(char => transCase(char)).join('');
} 问题是只适用于大小写字母区间,不然表现会很怪异。 优化的时候可以做做边界条件。思路应该没问题。 |
马上想到的也是一楼的方法,另外也可以: function swapString(str) {
var result = ''
for (var i = 0; i < str.length; i++) {
var c = str[i]
if (c === c.toUpperCase()) {
result += c.toLowerCase()
} else {
result += c.toUpperCase()
}
}
return result
}
swapString('ADasfads123!@$!@#') // => 'adASFADS123!@$!@#' |
@iotale transStr('adASjOdapASJO!@#4123123.l124')
// "ADasJoDAPasjoA`CTQRSQRSNLQRT" |
|
'AbcDefGh'.replace(/[a-zA-Z]/g,function(a){ return /[a-z]/.test(a)?a.toUpperCase():a.toLowerCase(); }); |
用ASCII做了一下。
|
[].map.call(str, function(item){
return /[a-z]/.test(item) ? item.toUpperCase() : item.toLowerCase();
}).join(''); |
const reverse = str => {
let result = ''
for (let i = 0; i < str.length; i++) {
if (str[i] > 'Z') {
result += str[i].toUpperCase()
} else {
result += str[i].toLowerCase()
}
}
return result
} |
fn=(str)=>str.replace(/[A-Za-z]/g,c=>String.fromCharCode(c.charCodeAt()+(c<'['?32:-32)))
fn('-@A[Bc')//"-@a[bC" |
用了3种实现方法处理千万级别长度字符,对比了下时间,分享给大家,for循环+unicode转行相对较快
|
let a = 'aB1cd'; const gap = 'a'.charCodeAt() - 'A'.charCodeAt(); const test = (a) => a.replace(/[a-zA-Z]/g, (str, value) => { console.error(test(a)); |
正则实现: |
const str = 'AjklAJIBNiuh';
|
不用转成数组直接replace操作字符串 function transfer(str) {
return str.replace(/[a-zA-Z]/g, match => {
return /[a-z]/.test(match) ? match.toUpperCase() : match.toLowerCase()
})
} |
function transString(str) {
if(typeof str !== 'string') return
let strArr = str.split('')
return strArr.reduce((acc, cur) => acc += (cur === cur.toUpperCase() ? cur.toLowerCase() : cur.toUpperCase()))
} |
str = 'abcDEFg' |
function transString (str){
return Array.prototype.reduce.call(str, (acc, cur) => acc + (cur === cur.toUpperCase() ? cur.toLowerCase() : cur.toUpperCase()), '');
} |
|
|
/**
@param: {str}
*/
function reversal(str) {
let newstr = '';
for(let i = 0 ; i < str.length; i++) {
console.log(str[i].toUpperCase())
newstr += (str[i] === str[i].toUpperCase() ? str[i].toLowerCase() : str[i].toUpperCase())
}
return newstr;
}
console.log(reversal('AbC')) |
function tranStr(str) {
if (typeof str !== 'string') return ''
const splitStr = str.split('')
return splitStr.reduce((res, s) => {
if (/[a-z]/g.test(s)) {
res += s.toLocaleUpperCase()
} else if (/[A-Z]/g.test(s)) {
res += s.toLocaleLowerCase()
} else {
res += s
}
return res
}, '')
} |
/**
* 把一个字符串的大小写取反(大写变小写小写变大写),例如 ’AbC' 变成 'aBc'
* @param {*} str
*/
function tranStr2(str) {
if (typeof str !== 'string') return str
return str.replace(/[a-zA-Z]/g, function(s) {
return /[a-z]/g.test(s) ? s.toLocaleUpperCase() : /[A-Z]/g.test(s) ? s.toLocaleLowerCase() : s
})
} |
第一个字母没有转换吧== |
reverseCase = function (s) {
const isLowerCase = char => {
const range = ['a'.charCodeAt(), 'z'.charCodeAt()];
const charCode = char.charCodeAt();
return charCode >= range[0] && charCode <= range[1];
}
const isUpperCase = char => {
const range = ['A'.charCodeAt(), 'Z'.charCodeAt()];
const charCode = char.charCodeAt();
return charCode >= range[0] && charCode <= range[1];
}
return s.split('').map(char => {
if (isLowerCase(char)) return char.toUpperCase();
if (isUpperCase(char)) return char.toLowerCase();
}).join('');
} |
为啥不顺手把输出结果也贴出来 =。 = |
|
贴上去了 |
@wangminglmm 感谢,很直观 |
好像没看到用spread的,我写一下,用regex判断是否是字母, 以及用String.fromCharCode和String.prototype.charCodeAt()来切换大小写。
|
function transStr(str){
console.log(str)
return [...str].map((s) => {
console.log(s)
return s.toUpperCase() === s ? s.toLowerCase() : s.toUpperCase()
}).join('')
}
const strTest = 'AbC'
console.log(transStr(strTest)) |
function transStr(str) { |
|
function foo(s) { |
1、使用
|
// 大写的A-Z 转码比较结果比 小写a 要小
function turn(str){
const strArr = str.split('')
return strArr.map(key=> key < 'a' ? key.toLowerCase() : key.toUpperCase()).join('')
} |
let str = 'GuanWeiChang', result = '';
let UpperCaseIdx = [];
str.replace(/[A-Z]/g, function (match, idx) {
UpperCaseIdx.push(idx);
});
for (let i = 0; i < str.length; i++) {
const char = str[i];
result += UpperCaseIdx.includes(i) ? char.toLowerCase() : char.toUpperCase();
}
console.log(result); |
var str = 'AbC'
var reg = /([A-Z])|([a-z])/g
var result = str.replace(reg, function (match, p1, p2) {
if (p1) {
return p1.toLowerCase()
}
if (p2) {
return p2.toUpperCase()
}
})
console.log(result)//aBc |
const changeCase = (string) => {
return [...string].reduce((total, item) => {
total += (item.toLowerCase() == item ? item.toUpperCase() : item.toLowerCase())
return total
},'')
}
console.log(changeCase('AFDdhfaADvD')) |
"AabBcZz123,./".replace(/[a-zA-Z]/g, c=>c.charCodeAt(0)<91?c.toLowerCase(): c.toUpperCase());
// 得到 'aABbCzZ123,./' |
function letterUpperCaseReserve(string){ |
|
//我也写了用ascall码的,只适用于英文字母字符串
function reverseNum(str) {
let res = [];
let arr = str.split('');
let len = 'a'.charCodeAt();
for(let i=0;i<arr.length;i++){
let item = arr[i].charCodeAt();
res.push(String.fromCharCode(item>=len?item-32:item+32));
}
return res.join('');
} |
// Ascii码
let res = []
let str = 'Abc'
for (let val of str) {
// console.log(val);
if (val.codePointAt(0) >= 65 && val.codePointAt(0) <= 90) {
res.push(val.toLowerCase())
}
if (val.codePointAt(0) >= 97 && val.codePointAt(0) <= 122) {
res.push(val.toUpperCase())
}
}
console.log(res.join('')); |
天天开心!
|
let isUpperCase = (s = String) => s.charCodeAt() > 64 && s.charCodeAt() < 91;
let isLowerCase = (s = String) => s.charCodeAt() > 96 && s.charCodeAt() < 123;
let reverseCharCase = (str = String) =>
str
.split("")
.map((v, i) => (isLowerCase(v) ? v.toUpperCase() : v.toLowerCase()))
.join(""); |
天天开心!
|
function isLowerByAsciiCode(code){
return code > 64 && code <91;
}
function isUpperByAsciiCode(code){
return code > 96 && code <122;
}
function isLetterByAsciiCode(code){
return isLowerByAsciiCode(code) || isUpperByAsciiCode(code);
}
function flipLetter (str){
let newStr = '';
for (i of str) {
const asciiCode = i.charCodeAt();
if(isLetterByAsciiCode(asciiCode)){
newStr += String.fromCharCode(asciiCode ^ 32);
}else{
newStr += i;
}
}
return newStr;
}
flipLetter('adASjOdapASJO!@#4123123.l124');
// 'ADasJoDAPasjo!@#4123123.L124' |
|
let str = 'ADasfads123!@$!@#' |
已收到
|
天天开心!
|
正则判断一下是否为字母其余的不做修改
|
天天开心!
|
已收到
|
const reverseCase = rawString => {
const [lowerCharBase, lowerCharCap] = ['a'.charCodeAt(0), 'z'.charCodeAt(0)];
const [upperCharBase, upperCharCap] = ['A'.charCodeAt(0), 'Z'.charCodeAt(0)];
const transformCharList = rawString.split('').reduce((res, charItem) => {
const code = charItem.charCodeAt(0);
if (code >= lowerCharBase && code <= lowerCharCap) {
res.push(charItem.toUpperCase());
} else if (
code >= upperCharBase && code <= upperCharCap) {
res.push(charItem.toLowerCase());
} else {
res.push(charItem)
}
return res;
}, [])
return transformCharList.join('');
}
const inputString = 'AbC';
const result = reverseCase(inputString);
console.log(result); |
function swapCase(str) {
} // 示例 |
你的邮件我已收到,我会马上查看!
——————————————————————
现在的追逐梦想是为了日后能拥有美好的“那些年”!
|
天天开心!
|
已收到
|
The text was updated successfully, but these errors were encountered: