【问题标题】:C# remove a full string from an array based on a substring [duplicate]C#根据子字符串从数组中删除完整字符串[重复]
【发布时间】:2020-06-03 17:32:57
【问题描述】:

假设我有一个字符串数组

string[] my_array = { "XY:1234567;ZW:124", "XY:124252"};

用户输入string user_input = "1234567";

如何从my_array 中删除整个字符串

所以在删除 XY:1234567;ZQ:124 之后会根据部分输入删除

my_array = { "XY:124252" };

我的第一次尝试:

string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "1234567";
if(my_array.Contains(user_input))
    Console.WriteLine("Inside");
else
    Console.WriteLine("Not Inside");

输出Not Inside

我的第二次尝试:

string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "%1234567%"; // Tried % to do a partial string I think?
if(my_array.Contains(user_input))
    Console.WriteLine("Inside");
else
    Console.WriteLine("Not Inside");

输出Not Inside

我没有想法

【问题讨论】:

  • array.Contains 检查数组是否包含整个字符串。你想要array.Any(s => s.Contains(...))
  • 124如何部分匹配1234567?
  • 你应该使用 my_array.Any(s => s.Contains(user_input))

标签: c#


【解决方案1】:

你需要String.Contains()。试试看:

string[] my_array = { "XY:12345678;ZW:124", "XY:124252" };
string user_input = "1234567";
foreach( var item in my_array)
{
   if(item.Contains(user_input))
      Console.WriteLine("Inside");
   else
      Console.WriteLine("Not Inside");
}

【讨论】:

    猜你喜欢
    • 2018-06-09
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 2020-11-12
    • 2018-04-01
    • 2021-07-02
    相关资源
    最近更新 更多