簡單的問題。
我有一個名為“searchTerm”的字串變數和一個字串串列。我如何檢索與我的 searchTerm 變數匹配的某個元素而忽略空格。我一直試圖做但沒有成功的一個例子:
string searchTerm = "The Lord Of The Rings"
List<string> films = new List<string>(){ "Harry Potter", "Avangers", "The Lord Of The Rings", "Back to the future"};
string film = films.where(film => film.Contains(searchTerm, StringComparison.OrdinalIgnoreCase));
此代碼不起作用。請理解在電影串列中“指環王”字串在主詞之后有兩個空格,而searchTerm只有一個空格。
我嘗試了以下方法但沒有成功:
string film = films.where(film => film.Replace(" ","").Contains(searchTerm.Replace(" ",""), StringComparison.OrdinalIgnoreCase));
請你能幫我找到解決辦法嗎?謝謝
}
uj5u.com熱心網友回復:
我會使用“規范化”方法來洗掉連續的空格并用空格替換標點符號:
static string NormalizeWhiteSpacesAndPunctuations(string text)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
text = text.Trim();
StringBuilder sb = new StringBuilder(text.Length);
bool lastCharWasSpace = false;
foreach(char c in text)
{
if (char.IsWhiteSpace(c) || char.IsPunctuation(c))
{
// prevent consecutive spaces, only one should remain
if (!lastCharWasSpace)
{
sb.Append(' ');
lastCharWasSpace = true;
}
}
else
{
sb.Append(c);
lastCharWasSpace = false;
}
}
return sb.ToString().Trim();
}
現在這有效:
string searchTerm = "The Lord Of The Rings";
searchTerm = NormalizeWhiteSpacesAndPunctuations(searchTerm); // no-op in this case, but you should do it if searchTerm is an input
List<string> films = new List<string>() { "Harry Potter", "Avangers", "The Lord Of The Rings", "Back to the future" };
string film = films
.FirstOrDefault(film => NormalizeWhiteSpacesAndPunctuations(film).IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) >= 0);
.NET 小提琴:https : //dotnetfiddle.net/d8JM75
uj5u.com熱心網友回復:
為什么不使用簡單的正則運算式替換和字串比較?點網小提琴
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
string searchterm = "The Lord Of The Rings";
List<string> films = new List<string>(){ "Harry Potter", "Avangers", "The Lord Of The Rings", "Back to the future"};
string film = films
.FirstOrDefault(f => string.Equals(Regex.Replace(f, "\\s", ""), Regex.Replace(searchterm, "\\s", ""), StringComparison.CurrentCultureIgnoreCase));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383160.html
