英文:
Separating odd numbers in a string with '-'
问题
我正在尝试处理一串数字并对这些数字进行迭代。当两个相邻的数字都是奇数时,我想用'-'分隔它们。
例如,999463会变成9-9-9463。
const str = "999463"
const numberWithDash = []
for (let i = 0; i < str.length; i++) {
if (str[i] % 2 !== 0 && str[i + 1] % 2 !== 0) {
numberWithDash.push(str[i] + '-')
} else {
numberWithDash.push(str[i])
}
};
console.log(numberWithDash.join(''))
这会返回"9-9-9463-"。为什么会在我的代码末尾添加一个额外的破折号?我认为这是因为字符串中的最后一个数字是奇数,因此它通过了if语句,而不是else语句。
如果我修改为'i < str.length - 1',那么我就会完全去掉最后一个数字,所以这也不对。我认为我需要通过添加另一个条件来使我的if语句更加严格,以检查str[i]是否是数字,但不确定从哪里开始。
英文:
I am attempting to take a string of numbers and iterate through that number. When there are two odd numbers adjacent to one another, I want to separate them with '-'.
For example, 999463 would become 9-9-9463.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const str = "999463"
const numberWithDash = []
for (let i = 0; i < str.length; i++) {
if (str[i] % 2 !== 0 && str[i + 1] % 2 !== 0) {
numberWithDash.push(str[i] + '-')
} else {
numberWithDash.push(str[i])
}
};
console.log(numberWithDash.join(''))
<!-- end snippet -->
This returns "9-9-9463-". Why is this adding an additional dash on the end of my code? I think this is because the final number in the string is odd, thereby it is being passed through the if statement, instead of the else stament.
If I amend 'i < str.length -1' then I just cut off the last number entirely, so that isn't right either. I think I need to make my if statement stricter by adding another condition to check if str[i] is a number, but not sure where to start.
答案1
得分: 1
你可以只检查是否位于字符串末尾。无论如何,这是有道理的,因为在这种情况下你不想测试下一个字符(不存在):
if (str[i] % 2 !== 0 && i < str.length - 1 && str[i + 1] % 2 !== 0 ) {
为了让代码稍微易读一些,我可能会做一些调整:我们总是需要添加当前数字,有时希望添加一个短划线。
for (let i = 0; i < str.length; i++) {
numberWithDash.push(str[i])
if (str[i] % 2 !== 0 && str[i + 1] % 2 !== 0 && i < str.length - 1) {
numberWithDash.push('-')
}
}
英文:
You can just check whether you are at the end of the string. That makes sense anyway since you don't want to test the next character in that case (there is none):
if (str[i] % 2 !== 0 && i < str.length - 1 && str[i + 1] % 2 !== 0 ) {
I'd probably turn some things around to make it slightly easier to read: We always need to append the current digit. We sometimes want to append a dash.
for (let i = 0; i < str.length; i++) {
numberWithDash.push(str[i])
if (str[i] % 2 !== 0 && str[i + 1] % 2 !== 0 && i < str.length - 1) {
numberWithDash.push('-')
}
}
</details>
# 答案2
**得分**: 1
只是一个基于正则表达式的解决方案
**正则表达式演示:** https://regex101.com/r/z068Qf/1
```js
const str = "999463"
console.log(str.replace(/[13579](?=[13579])/g, '$&-'))
英文:
Just a regex-based solution
Regex Demo: https://regex101.com/r/z068Qf/1
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const str = "999463"
console.log(str.replace(/[13579](?=[13579])/g, '$&-'))
<!-- end snippet -->
答案3
得分: 0
尝试这个
const str = "999463"
const numberWithDash = []
for (let i = 0; i < str.length; i++) {
if (str[i] % 2 == 1 && str[i + 1] % 2 == 1 ) {
numberWithDash.push(str[i] + '-')
} else {
numberWithDash.push(str[i])
}
};
console.log(numberWithDash.join(''))
当你检查字符串的最后一个元素时,srt[i + 1] % 2
的结果是NaN。NaN !== 0
为true。我认为最好与1
进行比较。
英文:
Try this
const str = "999463"
const numberWithDash = []
for (let i = 0; i < str.length; i++) {
if (str[i] % 2 == 1 && str[i + 1] % 2 == 1 ) {
numberWithDash.push(str[i] + '-')
} else {
numberWithDash.push(str[i])
}
};
console.log(numberWithDash.join(''))
When you checking the last element in your string the result of srt[i + 1] % 2
is NaN. NaN !== 0
is true. I think better to compair with 1
.
答案4
得分: 0
将循环更改为 for (let i = 0; i < str.length - 1; i++) {...
,就像以前一样,然后在这个循环之后添加 numberWithDash.push(str[str.length - 1])
。我确定这是正确的解决方案代码。在循环中不需要检查最后一个字符。
英文:
Change your cycle to for (let i = 0; i < str.length - 1; i++) {...
as you did before, and after this for cycle add numberWithDash.push(str[str.length - 1])
. I am sure it is correct coding of your problem. You musn't check last character in your cycle.
答案5
得分: 0
你可以将数字视为数字数组,然后使用reduce函数。它检查前一个数字和当前数字是否都是奇数,以决定是否包含破折号。
请注意,由于n % 2
的结果要么是0要么是1,你不需要将它写成n % 2 === 1
来检查是否为奇数,因为数字1被视为true
。
console.log([...'999463'].reduce((a,c,i,r) =>
`${a}${r?.[i-1]%2 && c%2 ? '-' : ''}${c}`))
英文:
You can treat the number as an array of numbers, and then use reduce. It checks whether both the prior number and the current number are odd in order to decide to include a dash.
Note that since n % 2
will either be 0 or 1, you don't need to write it as n % 2 === 1
to check if it's odd, because the number 1 is treated as true
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log([...'999463'].reduce((a,c,i,r) =>
`${a}${r?.[i-1]%2 && c%2 ? '-' : ''}${c}`))
<!-- end snippet -->
答案6
得分: 0
你可以添加额外的条件 && i < str.length - 1
来确保在处理最后一个数字时不添加破折号。
但与其将破折号“推入”数组中,也许更简单的方法是从字符串创建一个数组,然后从末尾向开头迭代,在需要的地方进行 splicing
来插入破折号。
const str = '999463';
const arr = [...str];
const isOdd = n => n % 2 !== 0;
for (let i = arr.length - 1; i > 0; i--) {
if (isOdd(arr[i]) && isOdd(arr[i - 1])) {
arr.splice(i, 0, '-');
}
}
console.log(arr.join(''));
英文:
You could add an additional condition && i < str.length - 1
to ensure that a dash isn't added if you're processing the last number.
But rather than pushing
dashes into an array it might be simpler to create an array from the string, and then iterate from the end to the beginning, splicing
in dashes where required.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const str = '999463';
const arr = [...str];
const isOdd = n => n % 2 !== 0;
for (let i = arr.length - 1; i > 0; i--) {
if (isOdd(arr[i]) && isOdd(arr[i - 1])) {
arr.splice(i, 0, '-');
}
}
console.log(arr.join(''));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论