Having issue while extracting required part from a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chetan9529
    New Member
    • Aug 2013
    • 4

    Having issue while extracting required part from a string

    I have a string, and i want a specific part from that. String is: "Hello how are you doing." I want 4 letter after word "how" and 4 letter after word "you". Also want to add additional string in front that is Joy.
    So my final output should be like, "Joyare doi"
    Thanks
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    Hi chetan and welcome to bytes.com!
    I'm a little confused; you say you want the 4 letters after "how" but then "how" is in your answer. Should the answer maybe be "Joy are doi"?

    Comment

    • chetan9529
      New Member
      • Aug 2013
      • 4

      #3
      Sorry for confusion.. Answer should be look like:
      "Joyare doi"

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        OK, you'll need two functions from the String class: indexOf(String) and substring(int, int).
        The indexOf(String) function will allow you to find the first occurrence of a substring while substring(int, int) will extract a substring with the given indexes. Here's a short example of how to use them together:
        [code=java]String alphabet = "abcdefghijklmn opqrstuvwxyz";
        int beginIndex = alphabet.indexO f("fghi");
        System.out.prin tln(alphabet.su bstring(beginIn dex, beginIndex + 3));[/code] The output of the above code is fgh.
        This method can be applied to your problem easily.

        Comment

        Working...