I have String str, from which I want to extract the sub-string excluding a possible prefix "abc".

我有字符串str,我想从中提取子字符串,不包括可能的前缀“abc”。

The first solution that comes to mind is:

我想到的第一个解决办法是:

if (str.startsWith("abc"))
    return str.substring("abc".length());
return str;

My questions are:

我的问题是:

  1. Is there a "cleaner" way to do it using split and a regular expression for an "abc" prefix?

    使用split和“abc”前缀的正则表达式是否有“更干净”的方法?

  2. If yes, is it less efficient than the method above (because it searches "throughout" the string)?

    如果是,它是否比上面的方法效率更低(因为它在整个字符串中搜索)?

  3. If yes, is there any better way of doing it (where "better way" = clean and efficient solution)?

    如果是的话,有没有更好的方法(“更好的方法”=干净高效的解决方案)?

Please note that the "abc" prefix may appear elsewhere in the string, and should not be removed.

请注意,“abc”前缀可能出现在字符串的其他地方,不应该删除。

Thanks

谢谢

6 个解决方案

#1


28

Shorter than above code will be this line:

短于以上代码如下:

return str.replaceFirst("^abc", "");

But in terms of performance I guess there wont be any substantial difference between 2 codes. One uses regex and one doesn't use regex but does search and substring.

但是就性能而言,我想两个代码之间不会有什么实质性的区别。一个使用regex,一个不使用regex,而是搜索和子字符串。

更多相关文章

  1. 与==两个字符串的Java比较是假的? [重复]
  2. 将字符串拆分为字符串数组。
  3. java十进制字符串转十六进制字符串
  4. jQuery(JavaScript)获取文字(字符串)宽度(显示长度)
  5. Java将一个字符串中的多个连一起的空格变成单个空格

随机推荐

  1. Android View 绘制流程之三:draw绘制
  2. android相对布局 相对对齐
  3. 我的Android第一步
  4. Android学习―LinearLayout布局中实现左
  5. Android framework Watchdog的监控过程
  6. Android 四大组件的理解
  7. Android 利用 xml 文件实现 ImageView 的
  8. Android的消息机制源码分析
  9. Android——SQLite使用
  10. Android之实现滑动开关组件