有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是执行各种字符串操作的有效方法

我有一个脚本,我必须从字符串中提取字符串,获取最后一个索引,获取字符串中的第n个字符,比较,字符串是否包含字符串等。我想知道在java中对字符串执行此类操作的最佳方法/实践。我应该一直使用StringBuilder来执行上述操作吗。在少数情况下,我使用regular expressions来查找字符串。 那么我应该用什么呢? 场景是:必须找到大量的比较和索引。谢谢


例如:

    String name = "application/octet-stream; name=\"2012-04-20.tar.gz\""; // get 2012-04-20.tar.gz
    Pattern pattern = Pattern.compile("\"(.*?)\"");
    Matcher matcher = pattern.matcher(name);
    if (matcher.find()) {
        System.out.println(matcher.group(1));
    }

    String date = " Number 4, December 2013";
    String year = date.substring(date.lastIndexOf(" ")+1);
    String month = date.substring(date.indexOf(',')+2,date.indexOf(" ",date.indexOf(',')+2 ));
    date = year+getMonth(month)+"01";
    System.out.println(date);

和上面一样,字符串中还有许多其他的字符串提取


共 (3) 个答案

  1. # 1 楼答案

    所有这些操作都可以通过String类完成,请参见下面的方法

    extract string from strings

    String.substring()

    get the last index

    String.length()-1

    the last character

    s.charAt(s.length()-1)

    get nth character in a string

    String.charAt()

    comparisons

    String.compareTo()

    string contains a string or not

    String.contains()
    你也可以使用字符串。如有必要,在两个上都使用toLowerCase()

  2. # 2 楼答案

    处理大量字符串对象时,明智地使用String intern函数以节省堆空间并消除对象创建开销。有关更多信息,请参阅here

  3. # 3 楼答案

    因为您没有操作字符串,所以可以使用String或StringUtils而不是StringBuilder