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

如何将含#的字符串分割为指定数组并去除前缀#?

字符串分割方案:移除前缀#并拆分元素

以下是几种主流编程语言的实现方式,核心思路都是处理开头的空元素或直接移除无效#后,按#完成分割:

JavaScript

const str = "#foo=bar#dude";
const result = str.split('#').filter(item => item);
// 输出: ["foo=bar", "dude"]

split('#')会把原字符串分割成["", "foo=bar", "dude"],再通过filter过滤掉空字符串,就能得到目标数组。

Python

方案一:过滤空元素

s = "#foo=bar#dude"
result = [item for item in s.split('#') if item]
# 输出: ['foo=bar', 'dude']

方案二:先清首尾#再分割

s = "#foo=bar#dude"
result = s.strip('#').split('#')
# 输出: ['foo=bar', 'dude']

strip('#')会移除字符串开头和结尾的所有#,剩下的内容直接按#分割即可得到目标数组。

Java

方案一:流式过滤空元素

import java.util.Arrays;

public class SplitExample {
    public static void main(String[] args) {
        String str = "#foo=bar#dude";
        String[] result = Arrays.stream(str.split("#"))
                                .filter(s -> !s.isEmpty())
                                .toArray(String[]::new);
        // 输出: ["foo=bar", "dude"]
    }
}

方案二:移除开头#后分割

public class SplitExample {
    public static void main(String[] args) {
        String str = "#foo=bar#dude";
        String[] result = str.replaceFirst("^#", "").split("#");
        // 输出: ["foo=bar", "dude"]
    }
}

replaceFirst("^#", "")用正则匹配并移除字符串开头的#,剩余内容按#分割就能得到目标数组。

内容的提问来源于stack exchange,提问作者Sheldor the conqueror

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:23:15