Search code examples
ballerina

How to iterate a string in Ballerina?


I am trying to get each character of a string and do some formatting and produce a new string in Ballerina. How can I iterate character-wise ?

I am on Ubuntu 16.04 and Ballerina 0.975.0

Any suggestions?


Solution

  • Based on the available string functions, I could come up with the following solutions.

    Solution 1:

    string s = "This is my string";
    foreach c in s.split("") {
        io:println(c);    
    }
    

    Solution 2:

    string s = "This is my string";
    foreach i in 0..< lengthof s {
        io:println(s.substring(i, i+1));     
    }