- Java 编程示例
- 示例 - 主页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- 有用的 Java 资源
- Java - 快速指南
- Java - 有用的资源
如何用 Java 存储字符串
问题描述
如何存储字符串?
解决方案
以下示例存储字符串,并使用 emit() 方法释放它。
public class StringBuffer {
public static void main(String[] args) {
countTo_N_Improved();
}
private final static int MAX_LENGTH = 30;
private static String buffer = "";
private static void emit(String nextChunk) {
if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
System.out.println(buffer);
buffer = "";
}
buffer += nextChunk;
}
private static final int N = 100;
private static void countTo_N_Improved() {
for (int count = 2; count <= N; count = count +2) {
emit(" " + count);
}
}
}
结果
以上代码示例将生成以下结果。
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82
StringBuffer 和 StringBuilder 类用于创建可变字符串。
StringBuffer
public class HelloWorld {
public static void main(String []args) {
StringBuffer sb = new StringBuffer("hello");
sb.append("world");
sb.insert(0, " Tutorialspoint");
System.out.print(sb);
}
}
结果
以上代码示例将生成以下结果。
Tutorialspointhelloworld
java_strings.htm
广告