1

I'm currently porting a VB project to java and encountered a problem I'm stuck with.

I'm receiving a string which looks like the following:

HOST: xxx.xxx.xxx.xxx
DEFAULT: xxx.xxx.xxx.xxx 
OS: LINUX
ID: az150
LIB: eth15

newline at the end of each output, space after ":" I'd like to split those strings and use a switch case afterwards. Not sure if the order stays the same all the time.

the switch case would look something like this:

switch(aString)
{
case "HOST":
   String host = HOST Value (xxx.xxx.xxx.xxx);
   do something with it
   break;
...

default:
  break;
}

thanks!

12dollar
  • 645
  • 3
  • 17

1 Answers1

0

The String.split() method is able to solve the problem and even no regular expression is needed.

Suggest you have a string like

String string = "HOST: xxx.xxx.xxx.xxx\n"
        + "DEFAULT: xxx.xxx.xxx.xxx\n"
        + "OS: LINUX\n"
        + "ID: az150\n"
        + "LIB: eth15";

then you can get a key-value line as follows

String[] lines = str.split("\n");

for each line in the array, key and value could be achieved like

String[] entry = s.split(":");
String key = entry[0];
String value = entry[1].trim(); // omit whitespace

then you can put the key-value pair anywhere you want, such as Map, Property, Config, etc. And then the switch sentence will work well. You can also check whether the value is empty before using it since the value might contain nothing.

Yohn
  • 580
  • 5
  • 19