简体   繁体   中英

Loop in string and get word between 2 character

i have string like:

www.sample.com/cat-phone/cat-samsung/attrib-1_2/attrib-2_88/...

how to get last category , in this example , cat-samsung. and how to get 1_2 and 2_88 and ... and split 1 from 2 or 2 from 88.

i write this code to get value between / and / .

public void GetCodesAndPrice(string url,out List<int> listOfCodes, out List<int> listOfPrice )
{
    listOfCodes=new List<int>();
    listOfPrice = new List<int>();
    url = url.Substring(url.IndexOf('?')+1);
    var strArray = url.Split('/');
    foreach (string s in strArray)
    {
        if(s.ToLower().Contains("code"))
            listOfCodes.Add(GetIntValue(s));

        else if(s.ToLower().Contains("price"))
            listOfPrice.Add(GetIntValue(s));
    }

    // Now you have list of price in "listOfPrice" and codes in "listOfCodes",
    // If you want to return these two list then declare as out

}
public int GetIntValue(string str)
{
    try
    {
        return Convert.ToInt32(str.Substring(str.IndexOf('-') + 1));
    }
    catch (Exception ex)
    {

        // Handle your exception over here
    }
    return 0; // It depends on you what do you want to return if exception occurs in this function
}

this code work for get integer values . but i can,t get latest category , in this example , samsung. i want to get samung name and then convert value to id in the next operation.

There are some string function/method, which helps you to achieve your goal.

First is String.Substring(startindex, length)

Second is String.Split("symbol")

For Example:

string your_String = "www.sample.com/cat-phone/cat-samsung/attrib-1_2/attrib-2_88/";
string last_Cat = your_String.Substring((your_String.LastIndexOf("cat-") - 1), (your_String.IndexOf("attrib-") - 2));
   Console.WriteLine(last_Cat);
  for (int i = 0; i < your_String.Split("/").Length; i++) {
    if (your_String.Split("/")[i].ToString().IndexOf("attrib-") != -1) {
        strin attri += your_String.Split("/")[i].Split("-")[1].Split("_")[1].ToString();
        Console.WriteLine(all_attri);
    }
  }

(This is only an example to show you, how can you use these function in string manipulation.)

Regular Expressions are your friend here. They're made for slicing and dicing text. Here's a class that will do what you need:

class MyDecodedUri
{
  // regex to match strings like this: /cat-phone/cat-samsung/attrib-1_2/attrib-2_88/...
  const string PathSegmentRegex = @"
    /                      # a solidus (forward slash), followed by EITHER
    (                      # ...followed by EITHER
      (?<cat>              # + a group named 'cat', consisting of
        cat                #   - the literal 'cat' followed by
        -                  #   - exactly 1 hyphen, followed by
        (?<catName>\p{L}+) #   - a group named 'catName', consisting of one or more decimal digits
      ) |                  # OR ...
      (?<attr>             # + a group named 'attr', consisting of
        attrib             #   - the literal 'attrib', followed by
        -                  #   - exactly 1 hyphen, followed by
        (?<majorValue>\d+) #   - a group named 'majorValue', consisting of one or more decimal digits, followed by
        _                  #   - exactly one underscore, followed by
        (?<minorValue>\d+) #   - a group named 'minorValue', consisting of one or more decimal digits
      )                    #
    )                      #
    " ;
  static Regex rxPathSegment = new Regex( PathSegmentRegex , RegexOptions.ExplicitCapture|RegexOptions.IgnorePatternWhitespace ) ;

  public MyDecodedUri( Uri uri )
  {
    Match[] matches = rxPathSegment.Matches(uri.AbsolutePath).Cast<Match>().Where(m => m.Success ).ToArray() ;

    this.categories = matches
                      .Where(  m => m.Groups["cat"].Success )
                      .Select( m => new UriCategory( m.Groups["catName"].Value ) )
                      .ToArray()
                      ;

    this.attributes = matches
                      .Where( m => m.Groups["attr"].Success )
                      .Select( m => new UriAttribute( m.Groups["majorValue"].Value , m.Groups["minorValue"].Value ) )
                      .ToArray()
                      ;

    return ;
  }

  private readonly UriCategory[] categories ; 
  public UriCategory[] Categories { get { return (UriCategory[]) categories.Clone() ; } }

  private readonly UriAttribute[] attributes ; 
  public UriAttribute[] Attributes { get { return (UriAttribute[]) attributes.Clone() ; } }

  public Uri RawUri { get ; private set ; }

}

It uses a couple of custom helper types, one for category and one for attribute:

struct UriCategory
{
  public UriCategory( string name ) : this()
  {
    if ( string.IsNullOrWhiteSpace(name) ) throw new ArgumentException("category name can't be null, empty or whitespace","name");
    this.Name = name ;
    return ;
  }

  public readonly string Name  ;

  public override string ToString() { return this.Name ; }

}

struct UriAttribute
{
  public UriAttribute( string major , string minor ) : this()
  {
    bool parseSuccessful ;

    parseSuccessful = int.TryParse( major , out Major ) ;
    if ( !parseSuccessful ) throw new ArgumentOutOfRangeException("major") ;

    parseSuccessful = int.TryParse( minor , out Minor ) ;
    if ( !parseSuccessful ) throw new ArgumentOutOfRangeException("minor") ;

    return ;
  }

  public readonly int Major  ;
  public readonly int Minor ;

  public override string ToString() { return string.Format( "{0}_{1}" , this.Major , this.Minor ) ; }

}

Usage is dead simple:

string url = "http://www.sample.com/cat-phone/cat-samsung/attrib-1_2/attrib-2_88/" ;
Uri uri = new Uri(url) ;
MyDecodedUri decoded = new MyDecodedUri(uri) ;

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