【问题标题】:How to convert lowercase uppercase?(with if conditions on different digits.)如何转换小写大写?(不同数字的if条件。)
【发布时间】:2018-09-22 22:18:30
【问题描述】:

你好这是我第一次使用这个网站,我做了一些关于如何将小写字母转换为大写字母的研究,但仍然填充。要求是检查是否“偶数”,将偶数位字母转换为不同的类型(从下到上或从上到下)。以下是我的代码:

function question4(str,pos)
    {   var newLetter;
    var kkk=str;

        if (pos='even')
        {
            for (var i=0;i<str.length;i=i+2)
            {
                if (str[i].toString()==str[i].toString().toUpperCase())
                {
                    newLetter=str[i].toString().toLowerCase();
                    kkk[i]=newLetter;
                }else
                {
                    newLetter=str[i].toUpperCase();
                    kkk[i]=newLetter;
                }
            }
        }else if (pos='odd')
                    for ( i=0;i<str.length;i=i+2)
                    {
                        if (str[i]===str[i].toLowerCase())
                        {
                            alert('3');
                        }else if (str[i]===str[i].toUpperCase())
                        {
                            alert('4');
                        }
                    }
                    return kkk;
    }

要求是:编写一个函数,根据与pos参数函数的值匹配的位置来改变字符串中所有字符的大小写。函数(str,pos [偶数|奇数])。示例 ((‘abCd’, ‘odd’) 返回 Abcd)

更新:现在我已经让“奇数”条件起作用了,但是“甚至”仍然不起作用,任何人都可以看看为什么?

function question4(strr,pos) {
var result  ;
var sum="";
var aaa;

for (var i = 0; i <= strr.length - 1; i = i + 1)
{
    if (pos == "odd"&&i%2==0)
    {   aaa=strr.charCodeAt(i);

        if (aaa >= 65 && aaa <= 90 )
        {
            result = String.fromCharCode(aaa + 32);
        } else
            result = String.fromCharCode(aaa - 32);
    }
    else if (pos == "even"&&i%2==1)
    {
        if (aaa >= 65 && aaa <= 90 )
        {
            result= String.fromCharCode(aaa + 32);
        } else
            result = String.fromCharCode(aaa - 32);
    }else result=strr[i];
    sum+=result;
}


return sum;

}

【问题讨论】:

  • 那么这段代码可以工作吗?你还没有说明错误是什么。
  • 你确定 ('abCd', 'odd') 返回 Abcd 吗?我的意思是,a 的索引是 0 而不是 1
  • 我使用了我的函数,它从不改变字符串.....
  • 没关系,只要这个能用,我可以调整位置,但问题是这个功能根本不起作用,如果存在任何逻辑问题,我会感到困惑
  • 这不是c;字符串是不可变的

标签: javascript


【解决方案1】:

要实现这一点,你可以通过 char 连接 char 来构造一个字符串:

function question4(strInput, pos) {
  let str = ""; // The string to construct
  if (!pos || (pos !== "even" && pos !== "odd")) { // Validating pos
    throw "invalid pos";
  }
 for (var i=0;i<strInput.length;i++) // Looping on strInput
 {  
   let huPos = i + 1;
   if ((pos === "even" && huPos%2 == 1) ||
      (pos === "odd" && huPos%2 == 0)) { 
/* If we want switch odd and we are on even position or if we want switch even and we are on odd position, then we add the original char
*/
     str += strInput[i];
   }
   else {
     // In others case, we switch lower to upper and upper to lower
     let char = strInput[i];
     str += char == char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
   }
 }
 return str;
}
console.log(question4('abCdef', "odd")); // Return "AbcdEf"

Associated bin

编辑:

看到编辑后,我可以看到您想要在不使用 toLower/UpperCase 的情况下进行操作。正如评论中所述,我认为这在 js 中是一个坏主意,但要进行实验,您可以实现这一点:

const reverser = {
  "a": "a".charCodeAt(0),
  "z": "z".charCodeAt(0),
  "A": "A".charCodeAt(0),
  "Z": "Z".charCodeAt(0),
};
const conversionValueToLower = reverser.a - reverser.A;
const conversionValueToUpper = reverser.A - reverser.a;
function reverseChar(char) {
  var code = char.charCodeAt(0);
    // If you want to go from upper to lower
    if (code >= reverser.A && code <= reverser.Z) {
       // Simply add the difference between lower and upper
      return String.fromCharCode(code + conversionValueToLower);
    } // Same logic here
    else if (code >= reverser.a && code <= reverser.z) {
      return String.fromCharCode(code + conversionValueToUpper);
    }
  /**
  Or use if you want full digit
  if (code <= 90 && code >= 65) {
    return String.fromCharCode(code + 32);
  }
  else if (code >= 97 && code <= 122) {
    return String.fromCharCode(code - 32);
  }
  **/
  return char; // Other case return original char
}

function question4(strInput, pos) {
  let str = "";
  if (!pos || (pos !== "even" && pos !== "odd")) {
    throw "invalid pos";
  }
 for (var i=0;i<strInput.length;i++)
 {  
   let huPos = i + 1;
   if ((pos === "even" && huPos%2 == 1) ||
      (pos === "odd" && huPos%2 == 0)) {
     str += strInput[i];
   }
   else {
     str += reverseChar(strInput[i]);
   }
 }
 return str;
}
console.log(question4('abCdef', "odd")); // return "AbcdEf"

Associated bin

另一种方法是编写模仿 toLower/UpperCase 的 utils 函数

我在你的回答中也更正了你的代码,没有改变原来的逻辑

function question4(strr,pos) {
  var result  ;
  var sum="";
  var aaa;

  for (var i = 0; i <= strr.length - 1; i = i + 1)
  {
    if (pos == "odd"&&i%2==0)
    {   aaa=strr.charCodeAt(i);

     if (aaa >= 65 && aaa <= 90 )
     {
       result = String.fromCharCode(aaa + 32);
     } else if(aaa >=97&&aaa <=122)
     { result = String.fromCharCode(aaa - 32);}
     else {result=strr[i];}
    }
    else if (pos == "even"&&i%2==1)
    {   aaa=strr.charCodeAt(i);
     if (aaa >= 65 && aaa <= 90 )
     {
       result= String.fromCharCode(aaa + 32);
     } else if(aaa >=97&&aaa <=122)
     { result = String.fromCharCode(aaa - 32);}
     else {result=strr[i];}
    }else {result=strr[i];}
    sum+=result;
  }


  return sum;
}

console.log(question4("abCd", "odd")) // return Abcd;

【讨论】:

  • 谢谢,你所做的正是我所做的。我花了大约 2 天的时间才弄清楚这个解决方案,谢谢!
【解决方案2】:

我工作了两个晚上,终于成功了。虽然没有完全涵盖所有的情况,但差不多就可以了。

function question4(strr,pos) {
var result  ;
var sum="";
var aaa;

for (var i = 0; i <= strr.length - 1; i = i + 1)
{
    if (pos == "odd"&&i%2==0)
    {   aaa=strr.charCodeAt(i);

        if (aaa >= 65 && aaa <= 90 )
        {
            result = String.fromCharCode(aaa + 32);
        } else
            result = String.fromCharCode(aaa - 32);
    }
    else if (pos == "even"&&i%2==1)
    {   aaa=strr.charCodeAt(i);
        if (aaa >= 65 && aaa <= 90 )
        {
            result= String.fromCharCode(aaa + 32);
        } else if(aaa >=97&&aaa <=122)
        { result = String.fromCharCode(aaa - 32);}
        else {result=strr[i];}
    }else {result=strr[i];}
    sum+=result;
}


return sum;

}

【讨论】:

  • 你正在使用 C 策略。我认为将 UTF 代码用于如此微不足道的事情太多了。如果您使用的 if/else 越多,您的代码就越难阅读/调试。您必须正确命名变量。相同的代码被写了两次。你的第一个if 有一个错误(当你重复你的代码时会发生这种情况)。请检查我的答案并验证您是否愿意。请缩进并注释您的代码。
  • 我编辑了我的答案以满足您的需求,您可以查看
【解决方案3】:

这个问题的简单解决方案

// Function used to invert the letter case
const changeCase = c => {
  if (c === c.toUpperCase()) return c.toLowerCase()
  return c.toUpperCase()
}

const swapCaseConditional = (str, pos) => {
  // Use split method to convert string into array and map the array
  return str.split('').map((c, index) => {
    if (pos === 'even') {
      // if pos and index are even, change the letter case
      if (index % 2) return changeCase(c)
      return c
    }
    else {
      // if pos and index are odd, change the letter case
      if (!(index%2)) return changeCase(c)
      return c
    }
    // Convert to string
  }).join('')
}

console.log(swapCaseConditional('abCd', 'odd'))

【讨论】:

  • 你能评论代码吗?结果是错误的,它返回一个数组而不是一个字符串
猜你喜欢
  • 2021-06-21
  • 2013-02-04
  • 1970-01-01
  • 2015-08-07
  • 2011-01-16
  • 2019-06-25
  • 1970-01-01
  • 2022-11-11
  • 2011-12-13
相关资源
最近更新 更多