简体   繁体   中英

How to get the specific part of a string based on condition?

I have a requirement to get the substring of a string based on a condition.

String str = "ABC::abcdefgh||XYZ::xyz";

If input is "ABC", check if it contains in str and if it presents then it should print abcdefgh. In the same way, if input is "XYZ", then it should print xyz.

How can i achieve this with string manipulation in java?

If I've guessed the format of your String correctly, then you could split it into tokens with something like this:

String[] tokens = str.split("||");

for(String token : tokens)
{
    // Cycle through each token.


    String key = token.split("::")[0];
    String value = token.split("::")[1];

    if(key.equals(input))
    {
        // input being the user's typed in value.
        return value;
    }
}

But let's have a think for a minute. Why keep this in a String , when a HashMap is a much cleaner solution to your problem? Stick the String into a config file, and on load, some code can perform a similar task:

Map<String, String> inputMap = new HashMap<String, String>();

String[] tokens = str.split("||");

for(String token : tokens)
{
    // Cycle through each token.


    String key = token.split("::")[0];
    String value = token.split("::")[1];

    inputMap.put(key, value);
}

Then when the user types something in, it's as easy as:

return inputMap.get(input);

The idea is that, you should split your string with the delimiters of "::" and "||" , ie whichever of them is encountered it will be treated as a delimiter. So, the best way for achieving that is using regular expressions , I think.

String str = "ABC::abcdefgh||XYZ::xyz";
String[] parts = str.split("[::]|[/||]");

Map<String, String> map = new HashMap<String, String>();

for (int i = 0; i < parts.length - 2; i += 4) {
    if (!parts[i].equals("")) {
        map.put(parts[i], parts[i + 2]);
    }
}

Short and concise, your code is ready. The for loop seems weird, if anyone comes up with a better regex for splitting (to get rid of the empty strings), it will become cleaner. I'm not a regex expert, so any suggestions are welcome.

You could do it as follows:

    String[] parts = st.split("||");
    if (parts[0].startsWith("ABC")) {
        String[] values = parts[0].split("::");
        System.out.println(values[1]);
    } else {
        if (parts[1].startsWith("XYZ") {
            String[] values = parts[0].split("::");
            System.out.println(values[1]);
        }
    }

The above code will check first if ABC is there. If yes, it will print the result and then stop. If not, it will check the second section of the code to see if it starts with XYZ and then print the result. You can change it to suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM