Java add chars to a string(Java将字符添加到字符串)
问题描述
我在一个 java 程序中有两个字符串,我想以某种方式混合它们以形成两个新字符串.为此,我必须从每个字符串中提取一些组成字符并将它们添加以形成新字符串.我有这样的代码(this.eka 和 this.toka 是原始字符串):
String muutettu1 = new String();字符串 muutettu2 = 新字符串();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);
我正在获取 .charAt(x) 部分的数字,那么如何将字符转换为字符串?
只要使用 always use substring() 而不是
charAt()
在这种特殊情况下,值是可变的,因此,我们可以使用内置的 String
类方法 substring()
来解决这个问题(@see 下面的例子):
特定于 OP 用例的示例:
<代码>muutettu1 += toka.substring(0,1) + toka.substring(1,2) + eka.substring(2);muutettu2 += eka.substring(0,1) + eka.substring(1,2) + toka.substring(2);
概念示例,(即示例显示在尝试使用此概念解决问题时采用的一般方法)
<代码>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);
<块引用>
...其中 x,y,z 是保存要提取的位置的变量."
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()
In this particular case, the values are mutable, consequently, we can use the built in String
class method substring()
to solve this problem (@see the example below):
Example specific to the OP's use case:
muutettu1 += toka.substring(0,1) + toka.substring(1,2) + eka.substring(2);
muutettu2 += eka.substring(0,1) + eka.substring(1,2) + toka.substring(2);
Concept Example, (i.e Example showing the generalized approach to take when attempting to solve a problem using this concept)
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."
这篇关于Java将字符添加到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java将字符添加到字符串


基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01