[英]Removing all non letter characters from a string in C#
我想從字符串中刪除所有非字母字符。 當我說所有字母時,我指的是字母表或撇號之外的任何內容。 這是我的代碼。
public static string RemoveBadChars(string word)
{
char[] chars = new char[word.Length];
for (int i = 0; i < word.Length; i++)
{
char c = word[i];
if ((int)c >= 65 && (int)c <= 90)
{
chars[i] = c;
}
else if ((int)c >= 97 && (int)c <= 122)
{
chars[i] = c;
}
else if ((int)c == 44)
{
chars[i] = c;
}
}
word = new string(chars);
return word;
}
它很接近,但並不完全有效。 問題是這樣的:
[in]: "(the"
[out]: " the"
它給了我一個空格而不是“(”。我想完全刪除這個字符。
Char
類有一個方法可以提供幫助。 使用Char.IsLetter()
檢測有效字母(並額外檢查撇號) ,然后將結果傳遞給string
構造函數:
var input = "(the;':";
var result = new string(input.Where(c => Char.IsLetter(c) || c == '\'').ToArray());
輸出:
這'
您應該改用正則表達式 (Regex) 。
public static string RemoveBadChars(string word)
{
Regex reg = new Regex("[^a-zA-Z']");
return reg.Replace(word, string.Empty);
}
如果您不想替換空格:
Regex reg = new Regex("[^a-zA-Z' ]");
正則表達式會更好,因為這非常低效,但要回答您的問題,您的代碼的問題是您應該在 for 循環中使用 i 以外的其他變量。 所以,像這樣:
public static string RemoveBadChars(string word)
{
char[] chars = new char[word.Length];
int myindex=0;
for (int i = 0; i < word.Length; i++)
{
char c = word[i];
if ((int)c >= 65 && (int)c <= 90)
{
chars[myindex] = c;
myindex++;
}
else if ((int)c >= 97 && (int)c <= 122)
{
chars[myindex] = c;
myindex++;
}
else if ((int)c == 44)
{
chars[myindex] = c;
myindex++;
}
}
word = new string(chars);
return word;
}
這是有效的答案,他說他想刪除非字母字符
public static string RemoveNoneLetterChars(string word)
{
Regex reg = new Regex(@"\W");
return reg.Replace(word, " "); // or return reg.Replace(word, String.Empty);
}
private static Regex badChars = new Regex("[^A-Za-z']");
public static string RemoveBadChars(string word)
{
return badChars.Replace(word, "");
}
這將創建一個由字符類(括在方括號中)組成的正則表達式,用於查找不是(字符類中的前導^
)AZ、az 或 ' 的任何內容。 然后定義一個函數,用空字符串替換與表達式匹配的任何內容。
word.Aggregate(new StringBuilder(word.Length), (acc, c) => acc.Append(Char.IsLetter(c) ? c.ToString() : "")).ToString();
或者您可以用任何函數代替 IsLetter。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.