java 字符串加%,Java向字符串添加字符

在Java编程中,作者遇到了将两个字符串混合形成新字符串的问题。他们尝试使用`charAt()`方法和`substring()`方法来选取原始字符串的字符。代码示例展示了如何从每个字符串中提取特定位置的字符并组合成新的字符串。解决方案建议始终使用`substring()`而不是`charAt()`,以避免数值问题,并提供了当位置不是固定值时的变量处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have two strings in a java program, which I want to mix in a certain way to form two new strings. To do this I have to pick up some constituent chars from each string and add them to form the new strings. I have a code like this(this.eka and this.toka are the original strings):

String muutettu1 = new String();

String muutettu2 = new String();

muutettu1 += this.toka.charAt(0) + this.toka.charAt(1) + this.eka.substring(2);

muutettu2 += this.eka.charAt(0) + this.eka.charAt(1) + this.toka.substring(2);

System.out.println(muutettu1 + " " + muutettu2);

I'm getting numbers for the .charAt(x) parts, so how do I convert the chars to string?

解决方案

Just use always use substring() instead of charAt()

muutettu1 += toka.substring(0,1) + toka.substring(1,2) + eka.substring(2);

muutettu2 += eka.substring(0,1) + eka.substring(1,2) + toka.substring(2);

e.g. when the position arent isn't fixed values but variables do

muutettu1 += toka.substring(x,x+1) + toka.substring(y,y+1) + eka.substring(z);

muutettu2 += eka.substring(x,x+1) + eka.substring(y,y+1) + toka.substring(z);

where x,y,z are the variables holding the positions from where to extract

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值