在 C# 中查找具有特定字符串部分的固定长度字符串

本文关键字:字符串 字符串部 查找 | 更新日期: 2023-09-27 17:56:47

我想找到一个带有特定子字符串的固定长度的字符串。但是我需要像在SQL查询中那样做。

例:我有这样的字符串 -

AB012345
AB12345
AB123456
AB1234567
AB98765
AB987654

我想选择一开始有AB的字符串,然后有 6 个字符。这可以通过 SELECT * FROM [table_name] WHERE [column_name] LIKE 'AB______' 在 SQL 中完成(AB 后有 6 个下划线)。

所以结果将是:

AB012345
AB123456
AB987654

我需要知道是否有任何方法可以使用 C# 以这种方式选择字符串,通过使用 AB______.

在 C# 中查找具有特定字符串部分的固定长度字符串

您可以使用正则表达式来筛选结果:

List<string> sList = new List<string>(){"AB012345",
            "AB12345",
            "AB123456",
            "AB1234567",
            "AB98765",
            "AB987654"};
var qry = sList.Where(s=>Regex.Match(s, @"^AB'd{6}$").Success);

考虑到你有一个字符串数组:

string[] str = new string[3]{"AB012345", "A12345", "AB98765"};
var result = str.Where(x => x.StartsWith("AB") && x.Length == 8).ToList();

逻辑是如果它以 AB 开头,并且它的长度是 8。这是你最好的搭配。

这应该可以做到

List<string> sList = new List<string>(){
    "AB012345",
    "AB12345",
    "AB123456",
    "AB1234567",
    "AB98765",
    "AB987654"};
List<string> sREsult = sList.Where(x => x.Length == 8 && x.StartsWith("AB")).ToList();

第一个x.Length == 8确定长度,x.StartsWith("AB")确定字符串开头所需的字符

这可以通过使用字符串来实现。开头和字符串。长度函数如下:

public bool CheckStringValid (String input)
{
  if (input.StartWith ("AB") && input.Length == 8)
  {
     return true;
   }
  else
  {
     return false;
  }
}

如果字符串符合您的条件,这将返回 true。

希望这有帮助。

var strlist = new List<string>()
{
    "AB012345",
    "AB12345",
    "AB123456",
    "AB1234567",
    "AB98765",
    "AB987654"
};
var result = strlist.Where( 
    s => (s.StartsWith("AB") &&(s.Length == 8))
    ); 
foreach(var v in result)
{
    Console.WriteLine(v.ToString());
}