java - Java 中的字符串操作

标签 java string

我希望返回一个字符串,如下所示:

    Josephine Blow (Associate Professor, Math)
         Teaching Assignments: **(for each course write on a seperate line)**
          Course No.: xxx \t Section No.: xxxx \t Course Name: xxxx \t Day and Time: dayOfWeek - timeOfweek
          If no teaching assignments print: none

使用名为“teaches”的 ArrayList 变量,我可以从中获取所有信息。

我只是不明白我应该如何返回这种可能很长的字符串。 我应该使用某种字符串缓冲区吗?如何在每两个部分之间添加单独的行。

这是我的代码,为了清楚起见:

public String toString() {
            String s ="";
            int i=1;
            if (this.teaches.isEmpty()){
                return "none";
            }

            for(Section current: this.teaches){
            s=s+"Course No"+i+" Section No:"+current.getSectionNo()+" Course Name:"+current.getRepresentedCourse().getCourseName()+" Day and Time"+current.getTimeOfDay();
            }

            return new String (this.getName()+" (Associatr Professor, "+this.department+" )"+s);

}

最佳答案

是的,请使用StringBuilder :

public String toString() 
{
    StringBuilder builder = new StringBuilder();
    if (!this.teaches.isEmpty())
    {
        for(Section current: this.teaches)
        {
            builder.append("["
                   .append("Course No ")
                   .append(i)
                   .append(" Section No: ")
                   .append(current.getSectionNo())
                   .append(" Course Name: ")
                   .append(current.getRepresentedCourse().getCourseName())
                   .append(" Day and Time ")
                   .append(current.getTimeOfDay())
                   .append("]");
        }
    }

    return builder.toString();
}

或者,更好的是,有一个 Course类而不是一堆原始字符串,只需打印出 List<Course> ,调用其 toString()列表中每个条目的方法。

关于java - Java 中的字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5875099/

相关文章:

java - 使用 ProcessBuilder 启动 CMD

java - 通过脚本引擎 (jython) 从 Java 调用 Python?

java - 具有双重检查锁定的 map 同步

VB.NET IsNot 用于字符串比较

javascript - 检查字符串是否不包含重复字符

java - 递归方法打印字符串并递减1并为每个递归删除1个字母

java - 替换 SESSION_MANAGEMENT_FILTER 位置的默认过滤器

java - SWING - 绘制直线,编译时不会出现

c - 尝试连接字符串和字符时 C 中的段错误

python - 如何将嵌套字典列表转换为字符串,反之亦然