Extract substring from a string

后端 未结 10 1893
栀梦
栀梦 2020-12-02 19:55

what is the best way to extract a substring from a string in android?

相关标签:
10条回答
  • 2020-12-02 20:20

    you can use this code

        public static String getSubString(String mainString, String lastString, String startString) {
        String endString = "";
        int endIndex = mainString.indexOf(lastString);
        int startIndex = mainString.indexOf(startString);
        Log.d("message", "" + mainString.substring(startIndex, endIndex));
        endString = mainString.substring(startIndex, endIndex);
        return endString;
    }
    

    in this mainString is a Super string.like "I_AmANDROID.Devloper" and lastString is a string like"." and startString is like"_". so this function returns "AmANDROID". enjoy your code time.:)

    0 讨论(0)
  • 2020-12-02 20:20

    When finding multiple occurrences of a substring matching a pattern

        String input_string = "foo/adsfasdf/adf/bar/erqwer/";
        String regex = "(foo/|bar/)"; // Matches 'foo/' and 'bar/'
    
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input_string);
    
        while(matcher.find()) {
          String str_matched = input_string.substring(matcher.start(), matcher.end());
            // Do something with a match found
        }
    
    0 讨论(0)
  • 2020-12-02 20:22

    There is another way , if you want to get sub string before and after a character

    String s ="123dance456";
    String[] split = s.split("dance");
    String firstSubString = split[0];
    String secondSubString = split[1];
    

    check this post- how to find before and after sub-string in a string

    0 讨论(0)
  • 2020-12-02 20:26

    Here is a real world example:

    String hallostring = "hallo";
    String asubstring = hallostring.substring(0, 1); 
    

    In the example asubstring would return: h

    0 讨论(0)
提交回复
热议问题