Java add chars to a string

0 votes
asked Oct 31, 2009 by rize

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?

4 Answers

0 votes
answered Oct 31, 2009 by thomas-jung

The obvious conversion method is Character.toString.

A better solution is:

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

You should create a method for this operation as it is redundant.

The string object instatiantiation new String() is unnecessary. When you append something to an empty string the result will be the appended content.

0 votes
answered Oct 31, 2009 by jitter

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

0 votes
answered Oct 31, 2009 by alphazero
StringBuilder builder = new StringBuilder();
   .append(' ')  
System.out.println (builder.toString());
0 votes
answered Sep 15, 2017 by xiaogang

You can also convert an integer into a String representation in two ways: 1) String.valueOf(a) with a denoting an integer 2) Integer.toString(a)

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter