解决JAVA中字符串连接过慢的问题

it2022-05-05  119

如下的字符串连接在JAVA中是很慢的

// "static void main" must be defined in a public class. public class Main { public static void main(String[] args) { String s = ""; int n = 10000; for (int i = 0; i < n; i++) { s += "hello"; } } }

因为每一次延长字符串,都会把新的字符串拷到内存一块新的区域。

在 Java 中,由于字符串是不可变的,因此在连接时首先为新字符串分配足够的空间,复制旧字符串中的内容并附加到新字符串。

因此,总时间复杂度将是:

5 + 5 × 2 + 5 × 3 + … + 5 × n = 5 × (1 + 2 + 3 + … + n) = 5 × n × (n + 1) / 2,

也就是 O(n2)

解决方案:

// "static void main" must be defined in a public class. public class Main { public static void main(String[] args) { String s = "Hello World"; char[] str = s.toCharArray(); str[5] = ','; System.out.println(str); } }

使用toCharArray方法将字符串对象转化为字符数组,进行修改


最新回复(0)