用StringBuilder替换String?

时间:2017-07-27 08:21:46

标签: java string stringbuilder

我如何添加一个passStringBuilder()方法来创建一个与passString()完成相同工作的新方法?我需要使用StringBuilder对象而不是String对象。问候。

import intertech.MyDate;
public class PassByExperiment {

    public static void main(String[] args) {

        MyDate date = new MyDate(1, 20, 2008);
        System.out.println("Before passing an object " + date);
        passObject(date);

        System.out.println("After passing an object " + date);
        System.out.println("Before passing a primitive " +
        date.year);

        passPrimitive(date.year);
        System.out.println("After passing a primitive " +
        date.year);

        String x = date.toString();
        System.out.println("Before passing a String " + x);
        passString(x);
        System.out.println("After passing a String " + x); 
    }

    public static void passObject(MyDate d) {
        d.year = 2009;
    }

    public static void passPrimitive(int i) {
        i = 2010;
    }

    public static void passString(String s) 
    {
        int yearSlash = s.lastIndexOf('/');    
        s = s.substring(0, yearSlash + 1);
        s += "2012";

        System.out.println("New date string: " + s);
    }
}

这是我试过的:

public static void passStringBuilder(StringBuilder sb) {
   int yearSlashSB = sb.lastIndexOf('/');
   sb = sb.substring(0, yearSlashSB + 1);
   sb.append("2012");
   System.out.println("New date string: " + sb);
}

2 个答案:

答案 0 :(得分:0)

StringBuilder是一个可以像任何其他对象一样传递的类:

public static void passStringBuilder(StringBuilder sb) {
    int yearSlash = sb.lastIndexOf("/");
    sb.delete(yearSlash + 1, sb.length());
    sb,append("2012");
    System.out.println("New date string: " + sb.toString());
}

StringBuilder#substring返回String这是一个子字符串,保留sb。您需要删除某些字符。

基本上,StringBuilder包含字符并让您轻松操作它们。之后,它允许您从中提取String。您可以使用substringtoString

从Java 8开始,将它用于连接是没有意义的,因为String + String被Java自动更改为StringBuilder

答案 1 :(得分:-1)

如果没有纯粹的学术要求,我建议

public static void passStringBuilder(StringBuilder sb) {
    passString(sb.toString());
}