Mert
Mert

Reputation: 17

changing chars in input

for (int i= 0; i<inputAxiom.length(); i++)
{
  char c=inputAxiom.charAt(i);

  if (c == 'f' || c == 'h' || c == 'g')
  {
    if (rules[0].equals("f") || rules[0].equals("h")); 
    {
      inputAxiom = rules[1];
    }

Hello what I'm trying to do is get the user input from inputAxiom and for every f or h I want that part of the input to change

for example: if the inputAxiom = fff and the rules are f=f-h (which puts f at rules[0] and f-h at rules[1])

then it would change to f-hf-hf-h (changed each f to f-h)

Currently as soon as it finds f just changes to whole thing to f-h instead of f-h for every f

I think it has to do with

inputAxiom = rules[1];

but im not sure how to fix it

Upvotes: 0

Views: 62

Answers (2)

Christian Stewart
Christian Stewart

Reputation: 15519

You are currently changing the entire string:

inputAxiom = rules[1];

In order to change the specific characters, loop through your array like this:

var chars = inputAxiom.toCharArray();
for (int i= 0; i<inputAxiom.length(); i++)
{
  char c=inputAxiom.charAt(i);

  if (c == 'f' || c == 'h' || c == 'g')
  {
    if (rules[0].equals("f") || rules[0].equals("h")); 
    {
      chars[i] = rules[1];
    }
  }
}

If you want to insert that many characters, this will work::

inputAxiom = inputAxiom.replaceAll(rules[0], rules[2]).replaceAll(rules[1], rules[2]);

Upvotes: 0

Cyrille Ka
Cyrille Ka

Reputation: 15523

Strings are immutable. You can not change a part of an existing String instance. What you can do is to replace it with a modified copy of the original string.

For example, to replace all f with f-h, you would do:

outputAxiom = inputAxiom.replaceAll("f", "h-f");

Another possibility of manipulating strings is the StringBuilder API (do not mistake it for StringBuffer, which it's not recommended anymore).

Upvotes: 1

Related Questions