Hello, i've recently been working on a way to take a user's input and depending on that it contains i will make some replacements in that certain string. For example , a user enters this input :
"if (AGE_X==10){\r\n"
+ " j=1;"
+ "AGE_X=5;"
+ " if(true){"
+ "m=4/AGE_Y;"
+ "}"
+ "}";
i want to create a variable for every type of reference(i'm calling AGE_X and AGE_Y references) found in the string. By this i mean , when i find the first occurence of AGE_X i want to add a new line in front of the that line and create a variable like so: AgeX=
some string(AGE_X)... and then replace the every occurence of AGE_X with AgeX. Same will go for AGE_Y and and any other references found in the string(there will be a lot more such references , using these just for testing purposes).
So far my logic has been like this: split the large string so i can get the index of every reference and
= sign inside it. Then , because i will have multiple indexes for every reference and sign i will map every reference to a list of it's indexes and do the same for all the signs. Once i've done this i will search for the smallest index in each list and insert the newly created variable there(as described above). So far i've run into some trouble with the code, and I am not sure where the problem is though my guess would be that i either got stuck somehow in the
for loops or something went wrong with the mapping. This is how the code looks so far(i've extracted some unnecessary methods so i must have missed and } somewhere):
The commented line
// text = TestSplitting.addDelimiters(text); is just a method that splits the string into pieces. Created it because the user will not be allowed spaces as i've placed them now in the
text1 string so the method will parse that string and split it as necessary. So far i'm getting a result like this :
Reference AGE_X at position 3 has closest index at 0
Reference AGE_X at position 46 has closest index at 43
Reference AGE_Y at position 67 has closest index at 64
which is accurate, but i'm not sure how i have to proceed in order to map the each reference to it's value list properly and do what i described above(as you can see in some of the commented System.out.println the mapping doesn't work properly). For example the
System.out.println("references-> " + references); will result in something like this:
references-> {AGE_X=[3]}
references-> {AGE_X=[46]}
references-> {AGE_Y=[67], AGE_X=[46]}
and i have no idea why it adds another
AGE_X=[46] at the end.
If i didn't explain my issue clear enough please let me know and i will do my best to explain properly.
Any help would be greatly appreciated, i've been stuck at this for a while now and i think i'm missing some obvious things which i might not have missed if i was looking at it with fresh eyes. Also any suggestions on how to improve my code or logic are also more than welcome