Finding the character location of the 30th occurance of a substring in a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Maxington
    New Member
    • Feb 2008
    • 4

    Finding the character location of the 30th occurance of a substring in a string

    The problem I am left with is that I need to split a string into substrings and determine the character location of the 30th occurance of "\n" string.

    I have a string that has "\n" within it and I am looking for a way to know how many characters the string has from 0 to the 30th occurance of "\n" within the main string

    I have considered a string.split or indexOf but can't wrap my head around how to determine the character location of the 30th occurance part.

    Any ideas?
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    If you're not sure how to use the split(), conisder:
    IndexOf() has an overload that takes an index of where to start looking.

    So if you have the string:
    string s="fred ran fast and fast is good"

    and wanted the location of the 4th space " ", you could so something like this:
    Code:
    int spot=0;
    spot=s.IndexOf(" ",spot);
    if (spot!=-1)
    {//found one, and now spot =4
    }

    So you could loop that with say:
    Code:
    int spot=-1;
    string s="fred ran fast and fast is good";
    for(int i=0;i<30;i++)
    {
       spot=s.IndexOf(" ",spot+1);//make sure you start on the next character
       if(spot==-1)
       {//could not find another " ", so exit and leave spot at -1
          break;//if you don't exit, it will start over again and possibly give you the wrong value
       }
    }
    //when the loop exists, spot will either be a -1 meaning there were not enough occurances, or the index where the 30th character is

    Another possibility is to examine the characters in the string:
    Code:
    string s="fred ran fast and fast is good";
    int count=0;
    int spot=-1;
    for(int i=0;i <s.Length;i++)
    {
       if(s[i]==' ')
       {
          count++;
       }
       if(count==30)
       {
          spot=i;
          break;//leave the for loop
       }
    }
    //now spot will either be -1 or the index of the 30th " "
    //you can adjust to be the \n character you wanted

    As for Split:
    Code:
    string s="fred ran fast and fast is good";
    int spot=0;
    string[] pieces=s.Split(' ');
    if (pieces.Length>30)
    {//check to make sure there are enough pieces
       for(int i=0;i<pieces.Length;i++)
       {
          //you should add a 1 because the Split() will remove the split character
          spot+=pieces[i].Length+1;
       }
    }
    else
    {
       spot=-1;//not enough
    }
    //now spot will either be -1 or index of the 30th  " "

    Comment

    • Maxington
      New Member
      • Feb 2008
      • 4

      #3
      Yes, this worked.

      Thank you.

      Comment

      Working...