User1997
User1997

Reputation: 17

split a string and print contents in java

I am trying to split a String and print the contents of it in front of certain print statements, but I am unable to do it using the for loop. Can someone help ?

The name of the String(s1) is formed using the City, temperature and Latitude. The fields are separated using comma. I want the output to be formatted as follows :

City : Madrid
Temperature : 23.97
Latitude : 40.4168 

And I want to print the details in front of the above three print statements. How can I do so?

public class SplitExample{

    public static void main(String[] args){
        
        String s1 = "Madrid,23.97,40.4168";
        String[] arrOfStr = s1.split(",",3);
        
        for(String a : arrOfStr)
            System.out.println(a);  
        
        }

}

Upvotes: 1

Views: 114

Answers (4)

user4910279
user4910279

Reputation:

Try this.

String s1 = "Madrid,23.97,40.4168";
String[] arrOfStr = s1.split(",", 3);
System.out.printf("City : %s%nTemperature : %s%nLatitude : %s%n", (Object[])arrOfStr);

output:

City : Madrid
Temperature : 23.97
Latitude : 40.4168

Upvotes: 0

Init_Rebel
Init_Rebel

Reputation: 68

Try this

 String s1 = "Madrid,23.97,40.4168";
        String[] arrOfStr = s1.split(",", 3);
        String[] metadata = {"City", "Temperature", "Latitude"};

        for (int i = 0; i < arrOfStr.length && i < metadata.length; i++) {
            System.out.println(metadata[i] + " : " + arrOfStr[i]);
        }

Upvotes: 0

shashank
shashank

Reputation: 75

    String s1 = "Madrid,23.97,40.4168";
    String[] arrOfStr = s1.split(",",3);
    
    System.out.println("1.City : "+arrOfStr[0]);  
    System.out.println("2.Temperature : "+arrOfStr[1]); 
    System.out.println("3.Latitude : "+arrOfStr[2]); 

Upvotes: 0

azro
azro

Reputation: 54168

Just use different print, and access array items by indices

String s1 = "Madrid,23.97,40.4168";
String[] arrOfStr = s1.split(",", 3);

System.out.println("City: " + arrOfStr[0]);
System.out.println("Temparature: " + arrOfStr[1]);
System.out.println("Latitude: " + arrOfStr[2]);

Or store the keys in an array too, and iterate on both using their indices

String s1 = "Madrid,23.97,40.4168";
String[] keys = new String[]{"City", "Temparature", "Latitude"};
String[] arrOfStr = s1.split(",", 3);

for (int i = 0; i < keys.length; i++) {
    System.out.println(keys[i] + ": " + arrOfStr[i]);
}

Upvotes: 2

Related Questions