在字符串中循环并在2个字符之间获取单词

时间:2014-01-30 18:07:14

标签: c# asp.net url url-routing

我的字符串如下:

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

如何获得最后一个类别,在本例中,cat-samsung。 以及如何获得1_2和2_88以及...并从88中将2或2分开1。

我编写此代码以获取/和/之间的值。

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
}

此代码适用于获取整数值。但我可以,在这个例子中,获得最新的类别,三星。我想获得samung名称,然后在下一次操作中将值转换为id。

2 个答案:

答案 0 :(得分:0)

有一些字符串功能/方法,可以帮助您实现目标。

首先是String.Substring(startindex, length)

其次是String.Split("symbol")

例如:

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);
    }
  }

(这只是一个向您展示的示例,如何在字符串操作中使用这些函数。)

答案 1 :(得分:0)

正则表达式是您的朋友。它们用于切片和切割文字。这是一个可以满足您需求的课程:

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 ; }

}

它使用了几种自定义帮助程序类型,一种用于类别,另一种用于属性:

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 ) ; }

}

用法很简单:

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) ;