题解 | #参数解析#
参数解析
https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function () {
// Write your code here
let shell = await readline();
let res = getParams(shell);
console.log(res.length);
for(let item of res){
console.log(item);
}
}()
function getParams(str){
let l = 0;
let tag = -1;
let res = [];
for(let i = 0; i < str.length; i++){
if(str[i] === ' ' && tag === -1){
if(i > l){
res.push(str.slice(l,i));
}
l = i + 1;
}else if(str[i] === '"'){
if(tag === -1){
tag = i + 1;
}else{
res.push(str.slice(tag, i));
tag = -1;
l = i + 1;
}
}
}
if(l < str.length){
res.push(str.slice(l));
}
return res;
}
设置左右指针 `l,r` 和一个字符串标志`tag`。初始情况下 `l = r = 0,tag = -1`。tag用来记录左`"`的索引。
右指针r向右移动,当r指向的字符为" "时,如果`tag = -1`,即表明l和r之间的字符串为一个参数,从字符串str中截取l-r,加入结果中,然后将l赋值为当前i+1(即跳过空格)。如果`tag != -1`,则表明此时应该忽略空格,而采用`"`进行分隔。
当r指向的字符为`"`时,如果`tag = -1`,则表明当前引号为左引号,将tag的值更新为i+1(即跳过当前左引号),如果`tag !=-1`,说明当前引号是右引号,则截取tag与i之间的字符,加入结果中,然后tag值更新为-1,l更新为i+1,直到r指向str末尾。
细节部分:
- 截取字符串时跳过空格和引号
- 截取前判断start和end是否相等,避免截到空串
- 循环结束之后可能还剩余一个参数没加入到结果中
上海得物信息集团有限公司公司福利 1166人发布