簡體   English   中英

c#包含字符串的一部分

[英]c# contains part of string

所以我有一個Materiel-objects列表。 在Materiel我有15個get和set方法。 我想構建一個搜索方法,循環列表中的所有對象,以及每個Materiel對象中的所有變量。 循環部分很容易,但我正在努力使用字符串包含部分。 搜索詞可以是例如“acto”,我應該得到“Tractor”的命中。 我已經嘗試過使用string-Contains類,但據我所知,它只檢查從位置0開始的字符串。所以“Tra”得到一個命中,但不是“acto”。

課程中是否有任何構建,或者我應該自己編程?

對不起,解釋不好。

我的代碼。 我現在看到我得到子串的命中,但也有其他結果:)

    protected void Button_search_Click(object sender, EventArgs e)
    {
        string searchTerm = TextBox1.Text.ToString().ToLower();

        TableRow row;
        TableCell cell;

        int rowNumber = 1;

        foreach (Materiell mat in allItems)
        {
            if (searchTerm.Contains(mat.itemID.ToString().ToLower()) ||
                searchTerm.Contains(mat.manufacturer.ToLower()) ||
                searchTerm.Contains(mat.model.ToLower()) ||
                searchTerm.Contains(mat.serialNo.ToLower()) ||
                searchTerm.Contains(mat.dateProd.ToString().ToLower()) ||
                searchTerm.Contains(mat.location.ToLower()) ||
                searchTerm.Contains(mat.mainCategory.ToLower()) ||
                searchTerm.Contains(mat.subCategory.ToLower()) ||
                searchTerm.Contains(mat.dateAcquired.ToString().ToLower()) ||
                searchTerm.Contains(mat.price.ToString().ToLower()) ||
                searchTerm.Contains(mat.ownerID.ToString().ToLower()) ||
                searchTerm.Contains(mat.extra.ToString().ToLower()) ||
                searchTerm.Contains(mat.textComment.ToLower()) ||
                searchTerm.Contains(mat.active.ToString().ToLower()))
            {
                row = new TableRow();
                row.ID = "row" + rowNumber.ToString();
                rowNumber++;

                cell = new TableCell();
                cell.Text = "<a href=\"#\" class=\"opendiv\">" + mat.itemID.ToString() + "</a>";
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.manufacturer.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.model.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.serialNo.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.dateProd.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.location.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.mainCategory.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.subCategory.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.dateAcquired.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.price.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.ownerID.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.extra.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.ownDefData.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.textComment.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = mat.active.ToString();
                row.Cells.Add(cell);

                Table1.Rows.Add(row);
            }
        }
    }

"some string".Contains("str")將返回true,你是否遇到了案例敏感性問題?

如果是這樣,你可以使用這個:

public static bool Contains(this string source, string toCheck, StringComparison comp) {
  return source.IndexOf(toCheck, comp) >= 0;
}

string title = "STRING";
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);

(取自Case insensitive'Contains(string)'

使用IndexOf

string searchWithinThis = "ABCDEFGHIJKLMNOP";
string searchForThis = "DEF";
int firstCharacter = searchWithinThis.IndexOf(searchForThis);

Console.WriteLine("First occurrence: {0}", firstCharacter);

如果未找到substring,則返回-1。 它非常有用,也可以知道字符串的位置。

對於屎和笑聲,我認為這是一個很好的午餐休息項目,為問題提出一個簡單但“優雅”的解決方案(據我了解:) :):

例如

// I made up a Material class for testing:
public class Materiel
{
    public string A { get; set; }
    public int B { get; set; }
    public DateTime? C { get; set; }
    public string D { get; set; }
    public Nested E { get; set; }
}     

// [...] usage:

foreach (var pattern in new[]{ "World" , "dick", "Dick", "ick", "2012", "Attach" })
    Console.WriteLine("{0} records match '{1}'", Database.Search(pattern).Count(), pattern);

輸出:

2 records match 'World'
1 records match 'dick'
1 records match 'Dick'
2 records match 'ick'
1 records match '2012'
2 records match 'Attach'

該代碼也支持

  • 正則表達式匹配
  • 任何屬性類型(例如可以為空的DateTimes或嵌套類)
  • 顯示哪個屬性與pattern / substring匹配

請享用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace AClient
{
    public class Materiel
    {
        public string A { get; set; }
        public int B { get; set; }
        public DateTime? C { get; set; }
        public string D { get; set; }
        public Nested E { get; set; }
    }

    public struct Nested
    {
        public string Data { get; set; }
        public override string ToString() { return string.Format("Extra: {0}", Data); }
    }


    public static class FullText
    {
        public class PropMatched<T> { public PropertyInfo Property; public T Item; }

        public static IEnumerable<PropMatched<T> > ByProperty<T>(this IEnumerable<T> items, string substr)
        {
            return items.ByProperty(new Regex(Regex.Escape(substr), RegexOptions.IgnoreCase));
        }

        public static IEnumerable<PropMatched<T> > ByProperty<T>(this IEnumerable<T> items, Regex pattern)
        {
            return items.Select(i => i.MatchingProperties(pattern)).Where(m => null != m);
        }

        public static IEnumerable<T> Search<T>(this IEnumerable<T> items, string substr)
        {
            return items.Search(new Regex(Regex.Escape(substr), RegexOptions.IgnoreCase));
        }

        public static IEnumerable<T> Search<T>(this IEnumerable<T> items, Regex pattern)
        {
            return items.Where(i => null != i.MatchingProperties(pattern));
        }

        public static PropMatched<T> MatchingProperties<T>(this T item, Regex pattern)
        {
            if (null == pattern || null == item) return null;

            var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
            var matches = from   prop in properties 
                          let    val = prop.GetGetMethod(true).Invoke(item, new object[]{}) 
                          where  pattern.IsMatch((val??"").ToString()) 
                          select prop;

            var found = matches.FirstOrDefault();
            return found == null ? null : new PropMatched<T> {Item = item, Property = found};
        }
    }

    class Client
    {
        private static readonly IEnumerable<Materiel> Database = new List<Materiel>
            {
                new Materiel {
                        A = "Hello", B = 1, C = null, D = "World",
                        E = new Nested {Data = "Attachment"}
                    },
                new Materiel {
                        A = "Transfigured", B = 2, C = null, D = "Nights",
                        E = new Nested {Data = "Schoenberg"}
                    },
                new Materiel {
                        A = "Moby", B = 3, C = null, D = "Dick",
                        E = new Nested {Data = "Biographic"}
                    },
                new Materiel {
                        A = "Prick", B = 4, C = DateTime.Today, D = "World",
                        E = new Nested {Data = "Attachment"}
                    },
                new Materiel {
                        A = "Oh Noes", B = 2, C = null, D = "Nights",
                        E = new Nested {Data = "Schoenberg"}
                    },
            };


        static void Main()
        {
            foreach (var pattern in new[]{ "World" , "dick", "Dick", "ick", "2012", "Attach" })
                Console.WriteLine("{0} records match '{1}'", Database.Search(pattern).Count(), pattern);

            // regex sample:
            var regex = new Regex(@"N\w+s", RegexOptions.IgnoreCase);

            Console.WriteLine(@"{0} records match regular expression 'N\w+s'", Database.Search(regex).Count());

            // with context info:
            foreach (var contextMatch in Database.ByProperty(regex))
            {
                Console.WriteLine("1 match of regex in propery {0} with value '{1}'",
                    contextMatch.Property.Name, contextMatch.Property.GetGetMethod().Invoke(contextMatch.Item, new object[0]));

            }
        }
    }
}
class SearchInString
{
    static void Main()
    {
        string strn= "A great things are happen with great humans.";
        System.Console.WriteLine("'{0}'",strn);

        bool case1= strn.StartsWith("A great");
        System.Console.WriteLine("starts with 'A great'? {0}", case1);

        bool case2= strn.StartsWith("A great", System.StringComparison.OrdinalIgnoreCase);
        System.Console.WriteLine("starts with 'A great'? {0} (ignoring case)", case2);

        bool case3= strn.EndsWith(".");
        System.Console.WriteLine("ends with '.'? {0}", case3);

        int start= strn.IndexOf("great");
        int end= strn.LastIndexOf("great");
        string strn2 = strn.Substring(start, end- start);
        System.Console.WriteLine("between two 'great' words: '{0}'", strn2);
    }
}
 Bool doesContain = "Tractor".Contains("acto");

確實會是真的。

包含集合的作品,在這個例子中,我認為字符串被視為字符集合。

http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

string.Contains方法確實在字符串中的任何位置查找子字符串。

"asdf".Contains("as") --> True
"asdf".Contains("sd") --> True
"asdf".Contains("df") --> True
"asdf".Contains("xy") --> False

但是,這種比較具有案例意義,因此如果您想進行不區分大小寫的搜索,則可能需要轉換大小寫:

"Asdf".Contains("as") --> False
"Asdf".Contains("As") --> True

"Asdf".ToUpper().Contains("as".ToUpper()) --> True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM