-2

Say if I have the string "George:45:185" that contains the information Name:age:height about a person; how would I go about reading these values individually from the string? The solution seems to be to separate the string at the ":" symbol and after that reading the values individually, but I can not get it to work.

How do I go about solving this?

SERO9
  • 13
  • 4
  • 3
    "*but I can not get it to work*" can we see your code? Use [edit] option to update your question. – Pshemo Mar 19 '23 at 20:04

2 Answers2

0

Use String#split to separate the parts.

var str = "George:45:185";
var parts = str.split(":");
String name = parts[0];
int age = Integer.parseInt(parts[1]);
int height = Integer.parseInt(parts[2]);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

In Java, you can use the split() method of the String class to split the string into an array of substrings based on a specified delimiter. In your case, you can split the string using the colon (":") delimiter as follows:

String info = "George:45:185";
String[] values = info.split(":");

This will create an array value that contains three elements: "George", "45", and "185". You can then access these values individually using array indexing:

String name = values[0];
int age = Integer.parseInt(values[1]);
int height = Integer.parseInt(values[2]);

Note that if you need to convert the age and height strings to integers, then you have to use the parseInt() method of the Integer class.