切换字符串中的数字

Switch numbers in string

本文关键字:数字 字符串      更新时间:2023-09-26

我有一个字符串,其中包含以空格分隔的唯一数字,如下所示:

"2 4 13 14 28 33"

需要一种快速有效的方法来切换一对形式:

switchNumbers(2, 28)
// result: "28 4 13 14 2 33"

我可以拆分字符串并搜索值,但这听起来很无聊。有什么更好的主意吗?

您可以利用array函数而不是strings

请参阅代码中的内联注释:

var str = "2 4 13 14 28 33";
// Don't use `switch` as name
function switchNumbers(a, b) {
    var arr = str.split(' ');
    // Convert string to array
    // Get the index of both the elements
    var firstIndex = arr.indexOf(a.toString());
    var secondIndex = arr.indexOf(b.toString());

    // Change the position of both elements
    arr[firstIndex] = b;
    arr[secondIndex] = a;

    // Return swapped string
    return arr.join(' ');
}

alert(switchNumbers(2, 28));

演示

也试试:

var numbers = "2 4 13 14 28 33";
function switchNum(from, to){
  return numbers.replace(/'d+/g, function(num){
    return num == from ? to : num == to ? from :  num
  })
}
alert(switchNum(2, 28)) //result: "28 4 13 14 2 33"

注意:不要使用 switch 作为函数名称,switch 是 JavaScript 的语句。

我无法判断这是否无聊,但至少它没有分裂和循环:)

function switchNumbers(str, x, y) {
  var regexp = new RegExp('''b(' + x + '|' + y + ')''b', 'g'); // /'b(x|y)'b/g
  return str.replace(regexp, function(match) { return match == x ? y : x; });
}
var s = "2 4 13 14 28 33";
document.write('<pre>' + switchNumbers(s, 2, 28) + '</pre>');

我敢肯定这不是最好的方法......但它有效..

var swapnums = function(x,first,second) {
    var y = x.split(" ");
    var locOfFirst = y.indexOf(first.toString());
    var locOfSecond = y.indexOf(second.toString());
    y[locOfFirst] = second.toString();
    y[locOfSecond] = first.toString();
    return y.join(" ");
};
var str = "2 4 13 14 28 33";
switchNumbers(2,28);  // call
function switchNumbers(a,b)
{

var split_ = str.split(" ");
var index_of_1 = split_.indexOf(a+"");
var index_of_2 =  split_.indexOf(b+"")
temp =  split_[index_of_1];
split_[index_of_1] = split_[index_of_2] ;
split_[index_of_2] = temp ;

split_.toString(" "); // Answer
}

这样的事情应该有效。

var str= "2 4 13 14 28 33";
function switchNumbers(a, b) {
    var arr = str.split(" ");
    var first= arr.indexOf(a), second = arr.indexOf(b);
    arr[first] = arr.splice(second, 1, arr[first])[0];
    return arr.join(" ");
}

杰斯菲德尔演示

我认为你最好的解决方案可能是使用JavaScript的原生替换方法来处理字符串。

W3Schools在这里有一个很好的低谷。它应该完全按照您想要的方式执行,但可能会替换您指定的所有数字,因此请务必说出类似 var replacement = str.replace("2 ", "28 ");

编辑:指出了一个很好的缺陷。相反,您可以尝试:

EDIT2:Opps,在原始代码中有一些缺陷。经过测试,工作正常!:)

    function replaceNumbers(x1, x2, str) {
        var strMod = " " + str + " "
        var x1Mod = " " + x1 + " "
        var x2Mod = " " + x2 + " "
        
        // Want to replace "farthest" first to ensure correct replacement.
        if (str.indexOf(x1Mod) > str.indexOf(x2Mod)) {
            strMod = strMod.replace(x1Mod, x2Mod)
            strMod = strMod.replace(x2Mod, x1Mod)
        } else {
            strMod = strMod.replace(x2Mod, x1Mod)
            strMod = strMod.replace(x1Mod, x2Mod)
        }
        
        return strMod.slice(1, strMod.length - 1)
    }
   var numbers = "2 4 13 14 28 33";
   alert(replaceNumbers(2, 33, numbers))