You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除字符串中指定字符之后的所有内容,以问号截取场景为例

字符串截取(保留首个?)实现方案

核心实现逻辑

  • 查找目标字符串中第一个?的索引位置
  • 若存在?,截取字符串从起始位到该索引+1的片段,即可保留问号
  • 若不存在?,可根据业务需求选择返回原字符串,或直接在末尾追加问号

常见编程语言实现示例

JavaScript 实现

function interceptToFirstQuestionMark(str) {
  const questionIndex = str.indexOf('?');
  // 存在问号则截取到问号后一位,不存在直接返回原串
  return questionIndex !== -1 ? str.slice(0, questionIndex + 1) : str;
}

// 测试用例
const testStr = '/example?idontwantthis';
console.log(interceptToFirstQuestionMark(testStr)); // 输出结果:/example?

Python 实现

def intercept_to_first_question_mark(s: str) -> str:
    question_index = s.find('?')
    return s[:question_index + 1] if question_index != -1 else s

# 测试用例
test_str = '/example?idontwantthis'
print(intercept_to_first_question_mark(test_str)) # 输出结果:/example?

Java 实现

public class StringInterceptUtil {
    public static String interceptToFirstQuestionMark(String str) {
        int questionIndex = str.indexOf("?");
        return questionIndex != -1 ? str.substring(0, questionIndex + 1) : str;
    }

    public static void main(String[] args) {
        String testStr = "/example?idontwantthis";
        System.out.println(interceptToFirstQuestionMark(testStr)); // 输出结果:/example?
    }
}

如果需要适配没有问号时强制追加问号的需求,只需修改问号不存在时的返回逻辑,在原字符串末尾拼接?即可

内容的提问来源于stack exchange,提问作者Borybar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:15:02