split string by indexOf

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • N9

    split string by indexOf

    Hi

    Anyone who can help about split string.

    string text = "History about a boy, who loves to play baseball with
    his friends."

    I like to find indexOf "play" and read the string 10 char left and 10
    char right

    The result: " loves to play baseball "

    but my problem is, if I indexOf "his", it fail, because, " friends."
    only had 9 char.

    It's the same problem at the start of text.

    anyone who can help ??

    //N9
  • Paul E Collins

    #2
    Re: split string by indexOf

    "N9" <nhiasy@gmail.c omwrote:
    but my problem is, if I indexOf "his", it fail, because, " friends."
    only had 9 char.
    Count through the string with a loop and stop if you go out of range, or
    add 10 spaces at start and end and trim the result.

    Eq.


    Comment

    • Marc Gravell

      #3
      Re: split string by indexOf

      Smells like homework?

      You need to adjust the ends if they go outside of the range...

      int pre = 10, post = 10;
      string text = "History about a boy, who loves to play baseball
      with his friends.",
      search = "play";
      int index = text.IndexOf(se arch);
      int start = index - pre, end = index + search.Length + post;
      if (start < 0) start = 0;
      if (end text.Length) end = text.Length;
      string subString = text.Substring( start, end - start);

      Marc

      Comment

      • Jon Skeet [C# MVP]

        #4
        Re: split string by indexOf

        On May 14, 9:44 am, Marc Gravell <marc.grav...@g mail.comwrote:
        Smells like homework?
        >
        You need to adjust the ends if they go outside of the range...
        >
        int pre = 10, post = 10;
        string text = "History about a boy, who loves to play baseball
        with his friends.",
        search = "play";
        int index = text.IndexOf(se arch);
        int start = index - pre, end = index + search.Length + post;
        if (start < 0) start = 0;
        if (end text.Length) end = text.Length;
        string subString = text.Substring( start, end - start);
        An alternative to the last four lines:

        int start = Math.Max(0, index-pre);
        int end = Max.Min(text.Le ngth, index+pre);
        string subString = text.Substring( start, end-start);

        Jon

        Comment

        • Jon Skeet [C# MVP]

          #5
          Re: split string by indexOf

          On May 14, 11:47 am, "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
          int end = Max.Min(text.Le ngth, index+pre);
          Sorry, this should be index+post, not index+pre.

          Jon

          Comment

          Working...