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