【问题标题】:Java substring string when specific string occurs出现特定字符串时的Java子字符串字符串
【发布时间】:2016-06-13 08:30:18
【问题描述】:

当出现子字符串时,我需要帮助来对字符串进行子字符串处理。 示例

初始字符串:123456789abcdefgh

字符串到子字符串:abcd

结果:1​​23456789

我检查了 substr 方法,但它接受索引位置值。我需要搜索子字符串的出现而不是传递索引?

【问题讨论】:

  • 您需要再检查一下javadoc。你需要的一切都在那里......提示:其中一些方法存在不止一种风格。
  • 是的,我需要先使用 IndexOf 方法 String before = str.substring(0, str.indexOf(substr));

标签: java string substring


【解决方案1】:

如果要从最后一个数字 (a) 中拆分字符串,则代码如下所示:

您可以将"a" 更改为字符串中的任何字符

package nl.testing.startingpoint;

public class Main {

    public static void main(String args[]) {
        String[] part = getSplitArray("123456789abcdefgh", "a");

        System.out.println(part[0]);
        System.out.println(part[1]);
    }

    public static String[] getSplitArray(String toSplitString, String spltiChar) {
        return toSplitString.split("(?<=" + spltiChar + ")");
    }
}

请记住,toSplitString.split("(?&lt;=" + spltiChar + ")"); 从该字符的第一次出现开始拆分。

【讨论】:

  • 不,我还需要找到其他职位,例如 (bcde)
  • @AlessioDiMarco,编辑了代码,只需将字符 "a" 更改为您要拆分的字符串中的任何字符!
【解决方案2】:

希望这可能会有所帮助:

public static void main(final String[] args)
{
    searchString("123456789abcdefghabcd", "abcd");
}

public static void searchString(String inputValue, final String searchValue)
{
    while (!(inputValue.indexOf(searchValue) < 0))
    {
        System.out.println(inputValue.substring(0, inputValue.indexOf(searchValue)));

        inputValue = inputValue.substring(inputValue.indexOf(searchValue) +
            searchValue.length());
    }
}

输出:

123456789
efgh

【讨论】:

    【解决方案3】:

    使用正则表达式,像这样

    static String regex = "[abcd[.*]]"
    
    public String remove(String string, String regex) {
        return string.contains(regex) ? string.replaceAll(regex) : string;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 2018-04-02
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      相关资源
      最近更新 更多