Den - Ben
Den - Ben

Reputation: 99

Insert several chars instead of one into string

I have a string with expression. For example the string is "a + b". I need insert float variables instead of that characters. "a" = 2.4494 and "b" = 5.545466. I convert variables to string and then make from strings with expression and with values char arrays.

expr = expressions.get(i)[0]; // string with expression
        for (int j = 0; j < valsListArray.length; j++) {//find characters and values
                                                        //they should have      
            String selection = (String) valsListArray[j].getSelectedItem(); //get 
                                                               //chosen character
            Float valueFloat = segmentAreas.get(j);          //get value
            String valueString = "" + valueFloat;
            char[] charexpr = expr.toCharArray();                           //
            char[] valueChar = valueString.toCharArray();
            char[] ch = selection.toCharArray();
            for (int jj = 0; jj < charexpr.length; jj++) {
                if (charexpr[jj] == ch[0]) {  
                    charexpr[jj] = valueChar[0];    //here is the problem
                }
            }
            String s =new String(charexpr);
            expr = s;

but I cant understand how insert the whole charArray instead one character...

Upvotes: 1

Views: 249

Answers (2)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

For inserting several chars in an array at once, consider using a StringBuilder instead. Here's how you'd use it:

StringBuilder sb = new StringBuilder("initial string");
sb.append("another string");
sb.append(new char[] {'c', 'h', 'a', 'r', 's'});
sb.append(1.0f);
String str = sb.toString();

Upvotes: 3

baby boom
baby boom

Reputation: 158

A string is immutable. therefore it is bad practice to try to mutate it.

use StrigBuilder object to manipulate strings, it has an insert() method that enables you to do just what you were asking.

Upvotes: 2

Related Questions