java stringbuilder 替换字符串_java中的经典问题StringBuilder替换String

遇到一个面试题:在下面的例子中用“+”运算符连接字符串与用StringBuilder对象的append方法连接字符串哪个性能比较优异。

下图是给出的例子,例一,使用“+”运算符连接字符串

711a4b52e0a7a218e4335296864e5cf0.png

fd19c2b918bdcd4452920808f4bc2280.png

例二,使用StringBuilder对象的append方法连接字符串

4fc355bd46d6af69ba687ee9f2128567.png

1fc12d3aaca57ef7aaf36d7575a5e61b.png

按照之前的经验,例一在经过java编译器编译之后,使用“+”运算符连接子符串的方式会被编译成使用StringBuilder对象append的方法。每次循环都会都会创建一个StringBuilder对象。所以使用例二的方式性能比较优异,因为例二只创建了一个StringBuilder对象。

但是我把例子中的代码修改了一下,把例子中的for循环换成while(true)。下面是我修改后的代码。

package com.belizer.String;

import java.util.Random;

/**

* Created by 47131 on 2018/2/24.

* 说明使用StringBuffer并不一定消耗的内存比使用String消耗的内存小,

* 具体情况还要具体分析

*

*/

public class Demo2 {

public static void main(String[] args) {

//fun1();//fun1不会内存溢出

//fun2();//fun2会内存溢出

//fun3();

fun4();

}

public static void fun1(){

String s="我";

while (true){

s=s+"我";

}

}

public static void fun2(){

StringBuffer sb=new StringBuffer("我");

while (true){

sb.append("我");

}

}

public static void fun3(){

String s="";

Random random=new Random();

while (true){

s=s+random.nextInt(1000)+" ";

}

}

public static void fun4(){

String s="";

Random random=new Random();

StringBuilder sb=new StringBuilder();

while (true){

sb.append(random.nextInt(1000)).append(" ");

}

}

}

注:例一对应fun3方法,例二对应fun4方法。

按照刚才的理解,fun3会在每次循环都创建一个StringBuilder对象,所以其消耗的内存会一直增加,直到内存溢出。

但是情况恰恰相反,内存溢出的fun4,也就是使用StringBuilder对象的append方法连接字符串会内存溢出。顿时懵逼了,求教。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
替换字符串的字符,您可以使用以下几种方法来实现。 1. 使用`replace()`方法:替换字符串的指定字符。 ```java String input = "Hello, world!"; String output = input.replace('o', 'x'); System.out.println("替换后的字符串:" + output); ``` 这段代码,我们使用`replace()`方法将字符串的字符`o`替换为字符`x`。输出将是"替换后的字符串:Hellx, wxrld!"。 2. 使用`replaceAll()`方法:使用正则表达式替换字符串的字符。 ```java String input = "Hello, world!"; String output = input.replaceAll("o", "x"); System.out.println("替换后的字符串:" + output); ``` 这段代码,我们使用`replaceAll()`方法将字符串的字符`o`替换为字符`x`。输出将是"替换后的字符串:Hellx, wxrld!"。请注意,`replaceAll()`方法的第一个参数是一个正则表达式,因此可以进行更复杂的匹配和替换。 3. 使用`StringBuilder`或`StringBuffer`进行字符替换: ```java String input = "Hello, world!"; StringBuilder builder = new StringBuilder(input); for (int i = 0; i < builder.length(); i++) { if (builder.charAt(i) == 'o') { builder.setCharAt(i, 'x'); } } String output = builder.toString(); System.out.println("替换后的字符串:" + output); ``` 这段代码,我们使用`StringBuilder`来构建一个可变字符串,并遍历字符串的每个字符。如果字符为`o`,我们将其替换为`x`。最后,我们将`StringBuilder`转换为字符串并输出结果。 根据您的具体需求,选择适合的方法来替换字符串的字符。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值