Java中的字符串操作
我希望返回一个字符串,如下所示:Java中的字符串操作,java,string,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
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
使用名为teachs的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:
或者,更好的做法是,使用一个课程类而不是一堆原始字符串,然后打印列表,为列表中的每个条目调用其toString方法。您不需要严格使用StringBuffer或StringBuilder。当Java连接两个字符串时,它在内部使用非常类似于StringBuffer的东西。直接使用StringBuffer稍微好一点,不过我认为您不会注意到这一点
从换行开始,请使用\n字符。您可以通过管道传输许多\n您喜欢的字符,这将在字符串中插入一些空行
例如:
s+="Course No"+i+" Section No:"+current.getSectionNo()+" CourseName:"+current.getRepresentedCourse().getCourseName()+" Day and Time"+current.getTimeOfDay()+"\n\n";
StringBuilder builder = new StringBuilder();
for(Section current: this.teaches){
builder.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());
}
将在每道菜之间留下一条空行
您可以使用以\开头的代码添加一些特殊字符。请参阅:是的,您可以使用StringBuffer或StringBuilder构建响应StringBuffer是线程安全的,但通常性能稍差,因此如果您不关心多线程,请使用StringBuilder 例如:
s+="Course No"+i+" Section No:"+current.getSectionNo()+" CourseName:"+current.getRepresentedCourse().getCourseName()+" Day and Time"+current.getTimeOfDay()+"\n\n";
StringBuilder builder = new StringBuilder();
for(Section current: this.teaches){
builder.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());
}
您可以使用\n包含换行符,但使用换行符时需要小心,因为它们可能依赖于系统,因此最好使用
System.getProperty("line.separator")
作为StringBuffer的替代方案,您可以使用StringBuilder,这是在不需要同步访问时推荐的 至于换行符,我建议询问系统什么是合适的行尾字符,如下所示:
System.getPropertyline.separator 或StringBuilder(如果通过单个线程访问)。并通过\n字符添加新行,例如Hello\n World。编译后,它将转换为StringBuilder或StringBuffer,无论如何我都忘了,所以最后它真的不重要。如何在我的实现中使用它?在每行的末尾按字面意思放\n,如果想留下空行,请放\n\n,toothis不正常:s=s+课程号+i+章节号:+current.getSectionNo+课程名称:+current.getRepresentedCourse.getCourseName+日期和时间+当前.getTimeOfDay\n;什么意思?\n必须像其他字符一样位于字符串内部。s+=一些行\n也不使用System.getPropertyline.separator-它是独立于平台的。+1嗯,我发现line.separator部分很有趣,很好。