在JavaScript中交换字符串的连续/相邻字符



示例字符串:astnbodei,实际字符串必须为santobedi。在这里,我的系统开始从字符串的左侧读取一对两个字符,首先是LSB,然后是该字符对的MSB。因此,santobedi被接收为astnbodei。字符串可以是字母和数字的组合,也可以是偶数或奇数长度的字符。

My attempt so far:

var attributes_ = [Name, Code,
Firmware, Serial_Number, Label
]; //the elements of 'attributes' are the strings
var attributes = [];
for (var i = 0; i < attributes_.length; i++) {
attributes.push(swap(attributes_[i].replace(//g, '').split('')));
}
function swap(array_attributes) {
var tmpArr = array_attributes;
for (var k = 0; k < tmpArr.length; k += 2) {
do {
var tmp = tmpArr[k];
tmpArr[k] = tmpArr[k+1]
tmpArr[k+1] = tmp;
} while (tmpArr[k + 2] != null);
}
return tmpArr;
}
msg.Name = attributes; //its to check the code
return {msg: msg, metadata: metadata,msgType: msgType}; //its the part of system code
当运行上面的代码片段时,我收到以下错误:

无法编译脚本:javax.script.ScriptException::36:14 Expected: but found (return {__if();^在第36行第14列

我不知道错误是怎么说的。我的方法对吗?有什么直接的方法吗?

您是否尝试成对地通过数组并使用ES6语法进行交换?

在ES6中你可以这样交换变量:[a, b] = [b, a]

方法如下:你的代码是无效的,因为return不允许在函数之外使用。

let string = "astnbodei";
let myArray = string.split('');
let outputArray = [];
for (i=0; i<myArray.length; i=i+2) {
outputArray.push(myArray[i+1]);
outputArray.push(myArray[i]);
}
console.log(outputArray.join(''));

字符串内的连续成对字符交换可以很容易地通过reduce任务解决…

function swapCharsPairwise(value) {
return String(value)
.split('')
.reduce((result, antecedent, idx, arr) => {
if (idx % 2 === 0) {
// access the Adjacent (the Antecedent's next following char).
adjacent = arr[idx + 1];
// aggregate result while swapping `antecedent` and `adjacent`.
result.push(adjacent, antecedent);
}
return result;
}, []).join('');
}
console.log(
'swapCharsPairwise("astnbodei") ...',
swapCharsPairwise("astnbodei")
);

问题中错误的原因是函数swap的位置. 然而,改变它的位置又给了我一个错误:

java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: javax.script.ScriptException: delight.nashornsandbox.exceptions.ScriptCPUAbuseException: Script used more than the allowed [8000 ms] of CPU time.

@dikuw的回答部分地帮助了我。下面的代码行对我有用:
var attributes_ = [Name, Code,
Firmware, Serial_Number, Label
]; //the elements of 'attributes' are the strings
var attributes = [];
for (var i = 0; i < attributes_.length; i++) {
attributes.push(swap(attributes_[i].replace(//g, '').split('')));
}
return {msg: msg, metadata: metadata,msgType: msgType};
function swap(array_attributes) {
var tmpArr = [];
for (var k = 0; k < array_attributes.length; k= k+2) {
if( (array_attributes[k + 1] != null)) {
tmpArr.push(array_attributes[k+1]);
tmpArr.push(array_attributes[k]);
}}
return tmpArr.join('');
}

最新更新