1

I want to split String without creating string array. Below is code

String output = "abc 0 0 222.1.2.3:12345 1.1.3.5:20000 55555";
        JSONArray listeningIpsArray = new JSONArray();
        if (StringUtils.isNotEmpty(output)) {
            String[] lines = output.split("\n");
            for (String line : lines) {
                if (StringUtils.isNotBlank(line)) {
                    String[] port = output.split("\\:");
                    for (String l : port) {
                        listeningIpsArray.put(l.trim());
                    }
                }
            }
            // String a[] =output.split("\\:");
            System.out.println("String" + listeningIpsArray);
        }
    }

When I run this code I got output as below. Array of 3 String elements is being created

String["abc 0 0 222.1.2.3","12345 1.1.3.5","20000 55555"]

But I need output in only one string as below.

String["abc 0 0 222.1.2.3 12345 1.1.3.5 20000 55555"]

Space between IP and port.

How can I do this ?

4
  • Why do you have String[] port = output.split("\\:"); if you don't want that? Commented Dec 26, 2018 at 12:35
  • 1
    Why dont you replace ":" with space." " String a = "abc 0 0 222.1.2.3:12345 1.1.3.5:20000 55555"; String r = a.replace(":"," "); System.out.println(r); Commented Dec 26, 2018 at 12:36
  • use StringBuilder and append all the splitted strings to builder with space and finally add it to listeningIpsArray as listeningIpsArray.put(builder.toString()); Commented Dec 26, 2018 at 12:37
  • 1
    if you really need to split the string, I would recommend to use StringUtils.join to join the strings by space after Commented Dec 26, 2018 at 12:39

2 Answers 2

1

If this String output = "abc 0 0 222.1.2.3:12345 1.1.3.5:20000 55555"; is your input, and you want "abc 0 0 222.1.2.3 12345 1.1.3.5 20000 55555" as output, all you have to do is use output.replace(":", " ") i.e., simply replace all the colons with space. Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to use replace instead of split method for your purpose:

String output = "abc 0 0 222.1.2.3:12345 1.1.3.5:20000 55555";
JSONArray listeningIpsArray = new JSONArray();
if (StringUtils.isNotEmpty(output)) {
    String[] lines = output.split("\n");
    for (String line : lines) {
        if (StringUtils.isNotBlank(line)) {
            listeningIpsArray.put(l.trim().replace(":"," "));
        }
    }
    System.out.println("String" + listeningIpsArray);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.