2.请写出函数,用于查找最长数字字符串的位置,例如输入”12abc3de33547f9g”,则返回8,即“33547”的开始下标位置
时间: 2024-03-09 10:45:58 浏览: 17
可以使用正则表达式来匹配数字字符串,然后遍历所有匹配到的数字字符串,找到最长的那个,并返回其起始下标位置。
下面是实现的代码:
```javascript
function findLongestNumStr(str) {
let regex = /\d+/g;
let match;
let maxLen = 0;
let startIndex = -1;
while ((match = regex.exec(str)) !== null) {
let len = match[0].length;
if (len > maxLen) {
maxLen = len;
startIndex = match.index;
}
}
return startIndex;
}
let str = '12abc3de33547f9g';
let index = findLongestNumStr(str);
console.log(index); // 输出 8
```
在上面的代码中,我们使用了正则表达式`\d+`来匹配数字字符串,然后在while循环中遍历所有匹配到的结果,找到最长的那个,并记录其起始下标位置。最后返回这个位置即可。
相关问题
请写出函数,用于查找最长数字字符串的位置,例如输入”12abc3de33547f9g”,则返回8,即“33547”的开始下标位置
可以使用正则表达式和循环来实现该函数,代码如下:
```javascript
function findLongestNumberString(str) {
let longestStart = -1; // 最长数字字符串的开始下标位置
let longestLength = 0; // 最长数字字符串的长度
let currentStart = -1; // 当前数字字符串的开始下标位置
let currentLength = 0; // 当前数字字符串的长度
for (let i = 0; i < str.length; i++) {
// 如果当前字符是数字,则更新当前数字字符串的长度和开始下标位置
if (/\d/.test(str[i])) {
if (currentStart === -1) {
currentStart = i;
}
currentLength++;
} else {
// 如果当前字符不是数字,则比较当前数字字符串和最长数字字符串的长度
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
currentStart = -1;
currentLength = 0;
}
}
// 如果最长数字字符串出现在字符串结尾,则需要再次比较一次
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
return longestStart;
}
// 示例
let str = "12abc3de33547f9g";
let start = findLongestNumberString(str);
console.log(start); // 输出 8
```
这个函数的思路是先遍历整个字符串,当遇到数字字符时,更新当前数字字符串的长度和开始下标位置,当遇到非数字字符时,比较当前数字字符串和最长数字字符串的长度,并更新最长数字字符串的长度和开始下标位置。最后再次比较一次,如果最长数字字符串出现在字符串结尾,则需要再次更新最长数字字符串的长度和开始下标位置。
.编写函数,用于判断输入的字符串是否由数字或字母组成,并统计字符个数
可以使用Python中的isalnum()方法来判断字符串是否只由数字或字母组成,再使用len()函数统计字符个数。下面是一个示例代码:
```python
def is_alnum(string):
"""
判断字符串是否只由数字或字母组成,并返回字符个数
"""
count = 0
for char in string:
if char.isalnum():
count += 1
else:
return False, count
return True, count
```
使用示例:
```python
string1 = "abcd1234" # 只由数字和字母组成
string2 = "abc!23" # 含有非数字或字母字符
string3 = "12345" # 只由数字组成
print(is_alnum(string1)) # 输出 (True, 8)
print(is_alnum(string2)) # 输出 (False, 3)
print(is_alnum(string3)) # 输出 (True, 5)
```
其中,函数返回一个元组,第一个元素表示输入字符串是否只由数字或字母组成,第二个元素表示字符个数。