This site requires JavaScript, please enable it in your browser!
Greenfoot back
444Jam444
444Jam444 wrote ...

2020/5/12

Neat way of getting a character at a specific index?

444Jam444 444Jam444

2020/5/12

#
Hi, I am trying to find a neat way of getting a character at a specific index of a string. I know to use .charAt(index), but I need it to be a string, not a char, and converting it to a string every time is a messy process.
newVar = String.valueOf(stringname.charAt(index));
gets quite messy when you need to do this for every comparison. What I want is to use a loop to find a certain letter in a string, then check if both charAt(index - 1) AND charAt(index + 1) matches a specific character.
//check if calculation contains any letters
        //regex: [a-zA-Z] means 'from "a" to "z" or from "A" to "Z" '
        if (finalCalculation.matches("[a-zA-Z]")){
            String character;
            for (int i = 0; i < finalCalculation.length(); i++){
                //get character at index i and convert to string
                character = String.valueOf(finalCalculation.charAt(i));
                //check if character is letter using regex (explained above)
                if (character.matches("[a-zA-Z]")){
                    if  //unfinished; meant to be 'if character at index -1 and index +1 is "*" '
                }
            }
        }
Note: I do NOT want to create an array of characters because the length of the string can vary greatly to the point where the array would be irrationally large, possibly lagging the program
danpost danpost

2020/5/12

#
The following does what you want:
newVar = ""+stringname.charAt(index);
I doubt it could be much cleaner than that.
444Jam444 444Jam444

2020/5/12

#
Thanks.
You need to login to post a reply.