{ }codelper
子串嵌套条件P0274

模仿 Python 的 a:b:c 切片

给出字符串 s 和 q 个切片询问。
对每个询问,输出按与 Python 的 s[a:b:c] 相同的规则切出的字符串。
设 s 的长度为 n,字符的位置从最前面的 0 数到 n − 1。
询问的形式是 a:b 或 a:b:c。
a、b、c 各是一个整数或者为空。
c 不存在或为空时,步长 c 为 1。
c 为正时:a 为空则起点为 0,b 为空则终点为 n。
给出的 a 若为负数就加上 n。
结果小于 0 就改成 0,大于 n 就改成 n,这就是起点。
b 也用同样的方法确定终点。
然后在位置小于终点期间,依次连接位置 起点、起点 + c、起点 + 2c、… 上的字符。
c 为负时:a 为空则起点为 n − 1,b 为空则终点为 −1(表示一直取到第 0 个字符)。
给出的 a 若为负数就加上 n。
结果小于 0 就改成 −1,大于 n − 1 就改成 n − 1,这就是起点。
b 也用同样的方法确定终点。
然后在位置大于终点期间,依次连接位置 起点、起点 + c、起点 + 2c、… 上的字符。
第一行给出 s,第二行给出 q,接下来 q 行每行一个询问。
对每个询问,在一行中输出切出的字符串。
若为空则输出 -。

输入
s 是由英文小写字母和数字组成的 1~200 个字符的字符串。
1 ≤ q ≤ 400。
询问中的 a、b、c 不为空时是 -1,000 到 1,000 的整数,c 不为 0。
询问中没有空格
输出
q 行
样例 1 · stdin
codelper
8
1:4
:3
-3:
::-1
6:1:-2
5:2
::3
-100:100
stdout
ode
cod
per
repledoc
eld
-
cee
codelper
样例 2 · stdin
abcdef
8
::-1
3::-1
:2:-1
-1:-7:-1
-7::-1
10:0:-1
::-1000
1:-1:1000
stdout
fedcba
dcba
fed
fedcba
-
fedcb
f
b
main.py
输入(stdin)

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

$ 就绪

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

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

只有 Python 的 s[a:b:c] 同时接受步长和负位置。
空的部分是 None,所以像 s[slice(None, None, -1)] 这样传进去,Python 会按步长的符号决定默认值。
其他语言要自己实现:JS・TS 的 slice(a, b) 接受负位置但没有步长(substring 把负数当作 0);Java substring(a, b)、C# Substring(起点, 长度)、Craykon 截取(起点, 个数) 越界会报错。
C++ substr(pos, len) 只容忍长度超出,pos 超过长度就是 out_of_range。
陷阱 ① 步长为负时,空的终点是 −1 而不是 0。
用 0 的话 ::-1 会漏掉第 0 个字符。
所以即使在 Python 里,把 s[a:b:c] 的空位填成 0 或 len(s) 也是错的(s[0:8:-1] 是空字符串)。
② 负位置先加 n,仍在外面就收拢。
步长为负时,小于 0 的收拢到 −1 而不是 0,所以 -100::-1 是空字符串。
③ 步长为负时,起点的上限是 n − 1 而不是 n。
允许到 n 会读到外面(Java・C#・Craykon 报错,C 是未定义行为)。
④ 分割时不要丢掉空的部分:Java 的 split(":") 会丢掉末尾的空部分,要用 split(":", -1)。
C 的 strtok 也会把连续的 :: 当成一个。
C++ std::optional、TS string | undefined 可以把“空”和 0 区分开来表示。

Pythonmain.py · 11 行
import sys lines = sys.stdin.read().split("\n")s = lines[0].strip()q = int(lines[1])out = []for line in lines[2:2 + q]:    # 빈 칸은 None: s[None:None:-1]처럼 기본값을 Python이 정한다(0을 넣으면 안 된다)    parts = [int(p) if p else None for p in line.strip().split(":")]    out.append(s[slice(*parts)] or "-")print("\n".join(out))
JavaScriptmain.js · 29 行
const lines = require("fs").readFileSync(0, "utf8").split("\n");const s = lines[0].trim();const n = s.length;const q = Number(lines[1]); // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다function fit(x, lo, hi) {  if (x < 0) x += n;  return Math.min(Math.max(x, lo), hi);} function pySlice(text) {  const [a, b, c] = text.trim().split(":"); // c가 없으면 undefined  const step = c ? Number(c) : 1;  let out = "";  if (step > 0) {    const start = a ? fit(Number(a), 0, n) : 0;    const stop = b ? fit(Number(b), 0, n) : n;    for (let i = start; i < stop; i += step) out += s[i];  } else {    // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다    const start = a ? fit(Number(a), -1, n - 1) : n - 1;    const stop = b ? fit(Number(b), -1, n - 1) : -1;    for (let i = start; i > stop; i += step) out += s[i];  }  return out || "-";} console.log(lines.slice(2, 2 + q).map(pySlice).join("\n"));
TypeScriptmain.ts · 31 行
import { readFileSync } from "node:fs"; const lines: string[] = readFileSync(0, "utf8").split("\n");const s = lines[0].trim();const n = s.length;const q = Number(lines[1]); // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다function fit(x: number, lo: number, hi: number): number {  if (x < 0) x += n;  return Math.min(Math.max(x, lo), hi);} function pySlice(text: string): string {  const [a, b, c]: (string | undefined)[] = text.trim().split(":"); // c가 없으면 undefined  const step = c ? Number(c) : 1;  let out = "";  if (step > 0) {    const start = a ? fit(Number(a), 0, n) : 0;    const stop = b ? fit(Number(b), 0, n) : n;    for (let i = start; i < stop; i += step) out += s[i];  } else {    // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다    const start = a ? fit(Number(a), -1, n - 1) : n - 1;    const stop = b ? fit(Number(b), -1, n - 1) : -1;    for (let i = start; i > stop; i += step) out += s[i];  }  return out || "-";} console.log(lines.slice(2, 2 + q).map(pySlice).join("\n"));
JavaMain.java · 42 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    static String s;    static int n;     // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다    static int fit(int x, int lo, int hi) {        if (x < 0) x += n;        return Math.min(Math.max(x, lo), hi);    }     static String pySlice(String text) {        String[] p = text.split(":", -1); // -1: 끝의 빈 칸도 버리지 않는다        boolean hasA = !p[0].isEmpty(), hasB = !p[1].isEmpty();        int step = p.length == 3 && !p[2].isEmpty() ? Integer.parseInt(p[2]) : 1;        StringBuilder out = new StringBuilder();        if (step > 0) {            int start = hasA ? fit(Integer.parseInt(p[0]), 0, n) : 0;            int stop = hasB ? fit(Integer.parseInt(p[1]), 0, n) : n;            for (int i = start; i < stop; i += step) out.append(s.charAt(i));        } else {            // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다            int start = hasA ? fit(Integer.parseInt(p[0]), -1, n - 1) : n - 1;            int stop = hasB ? fit(Integer.parseInt(p[1]), -1, n - 1) : -1;            for (int i = start; i > stop; i += step) out.append(s.charAt(i));        }        return out.length() > 0 ? out.toString() : "-";    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        s = in.readLine().trim();        n = s.length();        int q = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int t = 0; t < q; t++) out.append(pySlice(in.readLine().trim())).append('\n');        System.out.print(out);    }}
C#Main.cs · 47 行
using System;using System.Text; class Program{    static string s = "";    static int n;     // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다    static int Fit(int x, int lo, int hi)    {        if (x < 0) x += n;        return Math.Clamp(x, lo, hi);    }     static string PySlice(string text)    {        string[] p = text.Split(':'); // C#의 Split은 빈 칸도 남긴다        bool hasA = p[0] != "", hasB = p[1] != "";        int step = p.Length == 3 && p[2] != "" ? int.Parse(p[2]) : 1;        var sb = new StringBuilder();        if (step > 0)        {            int start = hasA ? Fit(int.Parse(p[0]), 0, n) : 0;            int stop = hasB ? Fit(int.Parse(p[1]), 0, n) : n;            for (int i = start; i < stop; i += step) sb.Append(s[i]);        }        else        {            // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다            int start = hasA ? Fit(int.Parse(p[0]), -1, n - 1) : n - 1;            int stop = hasB ? Fit(int.Parse(p[1]), -1, n - 1) : -1;            for (int i = start; i > stop; i += step) sb.Append(s[i]);        }        return sb.Length > 0 ? sb.ToString() : "-";    }     static void Main()    {        s = Console.ReadLine().Trim();        n = s.Length;        int q = int.Parse(Console.ReadLine().Trim());        var output = new StringBuilder();        for (int t = 0; t < q; t++) output.Append(PySlice(Console.ReadLine().Trim())).Append('\n');        Console.Write(output);    }}
C++main.cpp · 53 行
#include <algorithm>#include <iostream>#include <optional>#include <string>#include <vector> std::string s;int n; // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다int fit(int x, int lo, int hi) {    if (x < 0) x += n;    return std::clamp(x, lo, hi);} std::string pySlice(const std::string &text) {    std::vector<std::optional<int>> p; // 빈 칸은 값이 없는 optional    std::size_t from = 0;    while (true) {        std::size_t colon = text.find(':', from);        std::string part = text.substr(from, colon == std::string::npos ? std::string::npos : colon - from);        p.push_back(part.empty() ? std::nullopt : std::optional<int>(std::stoi(part)));        if (colon == std::string::npos) break;        from = colon + 1;    }    int step = p.size() == 3 && p[2] ? *p[2] : 1;    std::string out;    if (step > 0) {        int start = p[0] ? fit(*p[0], 0, n) : 0;        int stop = p[1] ? fit(*p[1], 0, n) : n;        for (int i = start; i < stop; i += step) out += s[i];    } else {        // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다        int start = p[0] ? fit(*p[0], -1, n - 1) : n - 1;        int stop = p[1] ? fit(*p[1], -1, n - 1) : -1;        for (int i = start; i > stop; i += step) out += s[i];    }    return out.empty() ? "-" : out;} int main() {    int q;    std::cin >> s >> q;    n = static_cast<int>(s.size());    std::string out;    for (int t = 0; t < q; t++) {        std::string line;        std::cin >> line;        out += pySlice(line) + '\n';    }    std::cout << out;    return 0;}
Cmain.c · 47 行
#include <stdio.h>#include <stdlib.h>#include <string.h> static char s[256];static int n; /* 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다 */static int fit(int x, int lo, int hi) {    if (x < 0) x += n;    return x < lo ? lo : x > hi ? hi : x;} int main(void) {    char line[64];    int q;    scanf("%255s %d", s, &q);    n = (int)strlen(s);    for (int t = 0; t < q; t++) {        scanf("%63s", line);        /* ':'로 칸을 나눈다. strtok는 빈 칸을 건너뛰어서 직접 나눈다 */        char *part[3] = {line, NULL, NULL};        int k = 1;        for (char *c = line; *c; c++)            if (*c == ':') {                *c = '\0';                part[k++] = c + 1;            }        int hasA = part[0][0] != '\0', hasB = part[1][0] != '\0';        int step = k == 3 && part[2][0] != '\0' ? atoi(part[2]) : 1;        char out[256];        int len = 0;        if (step > 0) {            int start = hasA ? fit(atoi(part[0]), 0, n) : 0;            int stop = hasB ? fit(atoi(part[1]), 0, n) : n;            for (int i = start; i < stop; i += step) out[len++] = s[i];        } else {            /* 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다 */            int start = hasA ? fit(atoi(part[0]), -1, n - 1) : n - 1;            int stop = hasB ? fit(atoi(part[1]), -1, n - 1) : -1;            for (int i = start; i > stop; i += step) out[len++] = s[i];        }        out[len] = '\0';        puts(len > 0 ? out : "-");    }    return 0;}
Craykonmain.cray · 64 行
s = 控制台.读行().去空白();n = s.长度;q = 控制台.读行().转数字(); // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다맞추기(x, lo, hi){    如果 (x < 0)    {        x = x + n;    }    返回 数学.较小值(数学.较大值(x, lo), hi);} 循环 (t = 0; t < q; t++){    p = 控制台.读行().去空白().分割(":");    걸음 = 1;    如果 (p.数量 == 3 && p[2] != "")    {        걸음 = p[2].转数字();    }    답 = "";    如果 (걸음 > 0)    {        시작 = 0;        끝 = n;        如果 (p[0] != "")        {            시작 = 맞추기(p[0].转数字(), 0, n);        }        如果 (p[1] != "")        {            끝 = 맞추기(p[1].转数字(), 0, n);        }        循环 (k = 시작; k < 끝; k = k + 걸음)        {            답 = 답 + s[k];        }    }    否则    {        // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다        시작 = n - 1;        끝 = -1;        如果 (p[0] != "")        {            시작 = 맞추기(p[0].转数字(), -1, n - 1);        }        如果 (p[1] != "")        {            끝 = 맞추기(p[1].转数字(), -1, n - 1);        }        循环 (k = 시작; k > 끝; k = k + 걸음)        {            답 = 답 + s[k];        }    }    如果 (답 == "")    {        답 = "-";    }    控制台.输出(답);}