{ }codelper
字符串下标字符P0053

字符第一次和最后一次出现的位置

第一行给出字符串 s,第二行给出一个字符 c。
输出 c 在 s 中第一次出现的位置和最后一次出现的位置,用一个空格隔开。
位置从 0 开始数。
如果 c 从未在 s 中出现,输出 "-1 -1"。
如果只出现一次,两个数相同。

输入
s 由小写英文字母和数字组成,长度 1 到 1,000。
c 是一个小写字母或数字
输出
第一次和最后一次的位置(没有则 -1 -1)
样例 1 · stdin
banana
a
stdout
1 5
样例 2 · stdin
hello
z
stdout
-1 -1
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

第一次和最后一次的位置:Python s.find(c)/s.rfind(c),JS/TS/Java indexOf/lastIndexOf,C# IndexOf/LastIndexOf(传 char 时按序数比较),C++ find/rfind,C strchr/strrchr。
Craykon 用 s.查找位置(c) 得到第一次的位置,最后一次则从末尾开始用循环判断 s[i] == c(没有从后往前找的成员)。
找不到时返回的值因语言而异:大多是 -1,但 Python 的 index/rindex 会抛出 ValueError,C++ 的 find 返回 std::string::npos(size_t 的最大值 18446744073709551615),直接输出就不是 -1。
C 的 strchr 返回指针或 NULL,要先判断是否为 NULL,再用 p - s 求位置。
单个字符在 Java、C#、C、C++ 中是 char(单引号 'a'),Python、JS、TS、Craykon 没有单独的类型,就是长度为 1 的字符串。

Pythonmain.py · 3 行
s = input()c = input()[0]print(s.find(c), s.rfind(c))
JavaScriptmain.js · 3 行
const [s, line] = require("fs").readFileSync(0, "utf8").split("\n").map((x) => x.trim());const c = line[0];console.log(s.indexOf(c), s.lastIndexOf(c));
TypeScriptmain.ts · 4 行
import { readFileSync } from "node:fs";const [s, line]: string[] = readFileSync(0, "utf8").split("\n").map((x) => x.trim());const c: string = line[0];console.log(s.indexOf(c), s.lastIndexOf(c));
JavaMain.java · 11 行
import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        String s = br.readLine().trim();        char c = br.readLine().trim().charAt(0);        System.out.println(s.indexOf(c) + " " + s.lastIndexOf(c));    }}
C#Main.cs · 11 行
using System; class Program{    static void Main()    {        string s = Console.ReadLine().Trim();        char c = Console.ReadLine().Trim()[0];        Console.WriteLine(s.IndexOf(c) + " " + s.LastIndexOf(c));    }}
C++main.cpp · 12 行
#include <iostream>#include <string> int main() {    std::string s;    char c;    std::cin >> s >> c;    size_t first = s.find(c);    size_t last = s.rfind(c);    std::cout << (first == std::string::npos ? -1 : (long long)first) << " "              << (last == std::string::npos ? -1 : (long long)last) << "\n";}
Cmain.c · 12 行
#include <stdio.h>#include <string.h> int main(void) {    char s[1001];    char c;    if (scanf("%1000s %c", s, &c) != 2) return 0;    char *first = strchr(s, c);    char *last = strrchr(s, c);    printf("%d %d\n", first ? (int)(first - s) : -1, last ? (int)(last - s) : -1);    return 0;}
Craykonmain.cray · 13 行
s = 控制台.读行().去空白();c = 控制台.读行().去空白()[0];first = s.查找位置(c);last = -1;循环 (i = s.长度 - 1; i >= 0; i--){    如果 (s[i] == c)    {        last = i;        跳出;    }}控制台.输出(first + " " + last);