WhoAmI
WhoAmI

Reputation: 1133

Iterate over String

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 iterate 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

Upvotes: 0

Views: 105

Answers (4)

Iterokun
Iterokun

Reputation: 2550

I'm not sure what would be the benefit of making a space separated list of values just to parse it again. Seems easier with a map of lists.

class GlobalVars {
    // TEST-DEV
    static String MY_URL1 = 'https://myurl.com'
    static String MY_URL2 = 'https://:6443'
    static Map MY_URLS = [
        'TEST': [
            MY_URL1,
            MY_URL2,
        ],
    ]
}
String ENV = 'TEST'
GlobalVars.MY_URLS[ENV].each {
    println it
}

No regex, no dynamically generated property names. If you want to avoid typos in the environment names you can put them into an enum.

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27220

You could do something like this...

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}"
}

String ENV = 'TEST'
for( name in GlobalVars."MYURLS_${ENV}".split(/\s+/)) {
    println name
}

Upvotes: 1

Matthias
Matthias

Reputation: 1354

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.

Upvotes: 0

Harvir
Harvir

Reputation: 131

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) + " ");
        }

Upvotes: 0

Related Questions