写一个ts函数判断是否以某些特定字符串开头或结尾接收3个参数:待测字符串特定字符串string以其开头还是结尾boolean返回特定字符串的下标
这是一个使用 TypeScript 编写的函数,用于判断一个字符串是否以某些特定字符串开头或结尾,并返回特定字符串的下标。
function checkString(str: string, specificStrings: string[], isStarting: boolean): number {
if (isStarting) {
for (let i = 0; i < specificStrings.length; i++) {
if (str.startsWith(specificStrings[i])) {
return i;
}
}
} else {
for (let i = 0; i < specificStrings.length; i++) {
if (str.endsWith(specificStrings[i])) {
return i;
}
}
}
return -1; // 如果没有匹配的特定字符串,则返回 -1
}
使用示例:
const str = "Hello, World!";
const specificStrings = ["Hello", "Hi", "World"];
const startingIndex = checkString(str, specificStrings, true);
const endingIndex = checkString(str, specificStrings, false);
console.log("Starting Index:", startingIndex); // 输出:0
console.log("Ending Index:", endingIndex); // 输出:2
在上面的示例中,待测字符串是 "Hello, World!",特定字符串数组是 ["Hello", "Hi", "World"]。首先通过 checkString 函数判断以特定字符串开头的情况,返回的下标是 0,因为 "Hello" 是第一个特定字符串。然后再判断以特定字符串结尾的情况,返回的下标是 2,因为 "World" 是第三个特定字符串。注意,下标从 0 开始计数。如果没有匹配的特定字符串,则返回 -1
原文地址: https://www.cveoy.top/t/topic/h6uw 著作权归作者所有。请勿转载和采集!