3 回答

TA貢獻1783條經驗 獲得超4個贊
幾個問題:
在您的循環中,您實際上只獲得與最后一個字符相關的選項。和或條款應該照顧它。
containsMore = containsMore || !(Char.IsSymbol(character) || Char.IsPunctuation(character));
然后,你最后需要一個 not。如果它不包含更多,那么它唯一的符號
return ! containsMore;
您可能還需要一個特殊情況來說明如何處理空字符串。不知道你想如何處理。如果空字符串應該返回 true 或 false,那將是您的選擇。
您可以使用單線完成此操作。請參閱這些示例。
string x = "@#=";
string z = "1234";
string w = "1234@";
bool b = Array.TrueForAll(x.ToCharArray(), y => (Char.IsSymbol(y) || Char.IsPunctuation(y))); // true
bool c = Array.TrueForAll(z.ToCharArray(), y => (Char.IsSymbol(y) || Char.IsPunctuation(y))); // false
bool e = Array.TrueForAll(w.ToCharArray(), y => (Char.IsSymbol(y) || Char.IsPunctuation(y))); // false

TA貢獻1834條經驗 獲得超8個贊
我相信 IsSymbol 方法會檢查一組非常具體的字符。你可能想做:
containsMore = (Char.IsSymbol(character) || Char.IsPunctuation(character)) ? false : true;
編寫了一個快速程序來顯示字符的結果并且確實顯示了癥狀。甚至可能是您的應用程序所需要的只是 IsPunctuation。
33/!: IsSymbol=False, IsPunctuation=True
程序
using System;
namespace csharptestchis
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 255; i++)
{
char ch = (char)i;
bool isSymbol = Char.IsSymbol(ch);
bool isPunctuation = Char.IsPunctuation(ch);
Console.WriteLine($"{i}/{ch}: IsSymbol={isSymbol}, IsPunctuation={isPunctuation} ");
}
}
}
}

TA貢獻1853條經驗 獲得超6個贊
首先,這個想法很簡單:你循環你的string,如果你遇到一個非符號的字符,返回false。直到結束,string你才不會遇到一個字符非符號。瞧,回來true。
public static bool ContainsOnlySymbols(string inputString)
{
// Identifiers used are:
bool containsMore = false;
// Go through the characters of the input string checking for symbols
foreach (char character in inputString)
{
containsMore = Char.IsSymbol(character) ? false : true;
if(!containsMore)
return false;
}
// Return the results
return true;
}
其次,你的代碼有問題,IsSymbol只有當你的角色在這些組中時才返回真
MathSymbol、CurrencySymbol、ModifierSymbol 和 OtherSymbol。
幸運的是,!不要在這些組中。這意味著 "!=" 返回false。
因此,您必須包括其他條件,例如:
public static bool ContainsOnlySymbols(string inputString)
{
// Go through the characters of the input string checking for symbols
return inputString.All(c => Char.IsSymbol(c) || Char.IsPunctuation(c));
}
或者您必須編寫自己的方法來確定哪些符號是可接受的,哪些是不可接受的。
或者,如果字符串不包含數字和字母,則可以將其視為符號。你可以做
public static bool ContainsOnlySymbols(string inputString)
{
// Go through the characters of the input string checking for symbols
return !inputString.Any(c => Char.IsLetterOrDigit(c));
}
- 3 回答
- 0 關注
- 220 瀏覽
添加回答
舉報