Home > other >  Itterate over String
Itterate over String

Time:12-13

So, I have this problem:

    #!/usr/bin/env groovy
    
    package com.fsfs.fdfs.fsf.utils
    
    class GlobalVars {
        // TEST-DEV
        static String MY_URL1 = "https://myurl.com"
        static String MY_URL2 = "https://:6443"
        static String MYURLS_TEST = "${MY_URL1} ${MY_URL2}"

}

So I want to itterate over my URLS depending on the environment. For example: in this ENV is TEST , but could be DEV, PROD and so on

 for( Name in GlobalVars."MYURLS_${ENV}".split(/\s /)) {

    }

I'm not sure how to achieve this. Basically, I want to iterate over a variable with a dynamic name. The variable contains at least 2 strings

CodePudding user response:

You can look into CharacterIterator methods current() to get the current character and next() to move forward by one position. StringCharacterIterator provides the implementation of CharacterIterator.

or for a simpler task can

Create a while loop that would check each index of the string or a for loop like this

 for (int i = 0; i < str.length(); i  ) {
 
            // Print current character
            System.out.print(str.charAt(i)   " ");
        }

CodePudding user response:

Iterating Strings works out of the box in Groovy:

"bla".each{println it}

.each{} closure will go over all characters of the string.

Same can be achieved with a more classical for-loop:

for(c in "foo") println c

Either way should work.

  • Related