从c#中的数组中删除类似的字符串
本文关键字:字符串 数组 删除 | 更新日期: 2023-09-27 18:25:45
假设我有一个字符串数组,如下所示:
string[] array = new string[6];
array[0] = "http://www.s8wministries.org/general.php?id=35";
array[1] = "http://www.s8wministries.org/general.php?id=52";
array[2] = "http://www.ecogybiofuels.com/general.php?id=6";
array[3] = "http://www.stjohnsheriff.com/general.php?id=186";
array[4] = "http://www.stjohnsheriff.com/general.php?id=7";
array[5] = "http://www.bickellawfirm.com/general.php?id=1048";
现在我只想存储一个类似的字符串,即http://www.s8wministries.org/general.php?id=35
,丢弃任何其他具有http://www.s8wministries.org
的字符串,并将其存储在另一个数组中。
请问我该怎么办?
我的尝试如下:-
//从数组中删除相似字符串,在另一个数组中只存储一个相似字符串
foreach (var olu in array)
{
string findThisString = olu.ToString();
string firstTen = findThisString.Substring(0, 15);
// See if substring is in the table.
int index1 = Array.IndexOf(array, firstTen); //substring is not in table
}
尝试使用字符串列表,这样您就有了包含URL的字符串列表,您可以使用URI类来比较域:
for(int i = 0; i < strList.Length; i++)
{
Uri uriToCompare = new Uri(strArray[i]);
for(int j = i+1; j < strArray.Length; j++){
Uri uri = new Uri(strArray[j]);
if( uriToCompare.Host == uri.Host){
strList.RemoveAt(j);
}
}
}
以下是我如何处理这个
- 初始化用于保存域名的哈希表或字典
- 循环浏览每个项目
- 使用"、"."、"/"执行字符串拆分操作etc作为分隔符-通过解析这些部分来查找域
- 检查哈希表中是否存在域名。如果是,则放弃当前条目。如果它不存在,请插入到哈希表中,并将当前条目添加到所选条目的新列表中
另一种选择是按字母顺序对条目进行排序。一次检查一个。选择具有域名的条目。跳过所有具有相同域名的下一个条目。当域名再次更改时,请选择下一个条目。
假设结果将存储在一个名为unique_array
的数组中,而您当前的数组则称为array
。伪代码如下:
bool found = false;
for(int i = 0; i < array_size; i++)
{ if(array[i] starts with "http://www.s8wministries.org")
{ if(found) continue;
found = true;
}
add array[i] to end of unique_array;
}
我会通过创建一个继承IEqualityComparer的类(利用这个问题的好答案)来实现更高的自动化:
public class PropertyComparer<T> : IEqualityComparer<T>
{
Func<T, T, bool> comparer;
public PropertyComparer<T>(Func<T, T, bool> comparer)
{
this.comparer = comparer;
}
public bool Equals(T a, T b)
{
return comparer(a, b);
}
public int GetHashCode(T a)
{
return a.GetHashCode();
}
}
一旦你有了这个类,你就可以像这样使用Distinct:
var distinctArray = array.Select(s => new Uri(s)).Distinct(new PropertyComparer<Uri>((a, b) => a.Host == b.Host));
这就留下了一个只包含不同域的数组。它是一个IEnumerable,所以您可能想要.ToList()
它或其他什么,或者将它从Uri
s还原回string
s。但我认为这种方法使代码可读性更强。
请尝试以下代码:
string[] array = new string[6];
array[0] = "http://www.s8wministries.org/general.php?id=35";
array[1] = "http://www.s8wministries.org/general.php?id=52";
array[2] = "http://www.ecogybiofuels.com/general.php?id=6";
array[3] = "http://www.stjohnsheriff.com/general.php?id=186";
array[4] = "http://www.stjohnsheriff.com/general.php?id=7";
array[5] = "http://www.bickellawfirm.com/general.php?id=1048";
var regex = @"http://www.['w]+.['w]+";
var distList = new List<string>();
var finalList = new List<string>();
foreach (string str in array)
{
Match match = Regex.Match(str, regex, RegexOptions.IgnoreCase);
if (match.Success)
{
var uniqueUrl = match.Groups[0].Value;
if (!distList.Contains(uniqueUrl))
{
distList.Add(uniqueUrl);
finalList.Add(str);
}
}
}
这里finalList包含所需的URL列表