Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java add chars to a string

Tags:

java

string

char

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?

like image 264
rize Avatar asked Oct 31 '09 14:10

rize


2 Answers

StringBuilder builder = new StringBuilder();
builder
   .append(this.toka.charAt(0))
   .append(this.toka.charAt(1))
   .append(this.toka.charAt(2))
   .append(' ')  
   .append(this.eka.charAt(0))
   .append(this.eka.charAt(1))
   .append(this.eka.charAt(2));
System.out.println (builder.toString());
like image 84
alphazero Avatar answered Oct 19 '22 03:10

alphazero


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."
like image 7
jitter Avatar answered Oct 19 '22 01:10

jitter