【问题标题】:Loop in string and get word between 2 character在字符串中循环并在 2 个字符之间获取单词
【发布时间】:2014-02-23 05:05:30
【问题描述】:

我有这样的字符串:

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

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

我编写这段代码来获取 / 和 / 之间的值。

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 name,然后在下一个操作中将 value 转换为 id。

【问题讨论】:

  • 到目前为止你尝试过做什么?您在这些尝试中遇到了什么问题?
  • 到目前为止你有什么写的吗?
  • 您是否尝试手动处理路由?

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


【解决方案1】:

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

第一个是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);
    }
  }

(这只是一个例子,告诉你如何在字符串操作中使用这些函数。)

【讨论】:

  • 对我不起作用。我想买猫三星。字符串结尾可以是任何单词
【解决方案2】:

正则表达式是你的朋友。它们是为切片和切割文本而设计的。这是一个可以满足您需要的课程:

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

【讨论】:

  • 嗨,尼古拉斯。谢谢您的回答。坚果我不知道你的课的用途。
猜你喜欢
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多