[英]c# cannot convert from string to char
我正在嘗試編寫一些代碼來顯示用戶提供給您的密碼中存在的任何符號。 我很新,正在嘗試使用isSymbol
但我被卡住了。 它說不能從字符串轉換為字符
using System;
namespace booleanprok
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a made up password:");
string madeUppw = Console.ReadLine();
Console.WriteLine(char.IsSymbol(madeUppw));
}
}
}
將字符串轉換為字符 試試這個
bool res;
Console.WriteLine("Enter a made up password:");
string madeUppw = Console.ReadLine();
foreach(char s in madeUppw){
res = Char.IsSymbol(s);//The char.issymbol takes characters as parameter
}
如果你有一個單一的字符串,你也可以試試
string str = "A";
char character = char.Parse(str);
或者
string str = "A";
char character = str.ToCharArray()[0];
“我正在嘗試編寫一些代碼來顯示用戶提供給您的密碼中存在的任何符號。”
鑒於上述聲明,我看到給出的示例代碼存在以下問題:
string
傳遞給IsSymbol()
方法,該方法需要一個char
。IsSymbol()
方法(這是一個bool
)的返回值,而不是字符本身。IsSymbol()
不會返回我們通常認為密碼中的符號的所有字符(如!
、 @
、 #
等)。 來自文檔: “符號是 UnicodeCategory 中以下類別的成員: MathSymbol
、 CurrencySymbol
、 ModifierSymbol
和OtherSymbol
。” 解決這些問題的一種方法是將任何不是字母或數字的字符視為“符號”,我們可以通過使用 Linq 擴展方法Where()
以及char.IsLetter()
和char.IsDigit()
方法。 然后我們可以在結果上使用string.Join
將字符輸出到控制台。
例如:
Console.Write("Enter a made up password: ");
string madeUpPwd = Console.ReadLine();
// Get the distinct characters that aren't Letters or Digits
IEnumerable<char> symbols = madeUpPwd
.Where(c => !char.IsLetter(c) && !char.IsDigit(c))
.Distinct();
// Output them to the console (separated by commas and wrapped in single quotes)
Console.WriteLine($"You entered the symbols: '{string.Join("', '", symbols)}'");
樣本輸出
(請注意,使用.Where(char.IsSymbol)
只會返回'$'
字符)
char.IsSymbol
接受char
參數,但您傳遞的是string
類型的參數。 如果您確定輸入的長度只有一個字符,或者您只想要第一個字符而忽略其他字符,則可以調用char.IsSymbol(madeUppw[0]);
但是,您可以使用Console.ReadKey
強制讀取單個字符並使用KeyChar
獲取值:
char madeUppw = Console.ReadKey().KeyChar;
Console.WriteLine(char.IsSymbol(madeUppw));
字符串由 0 個或多個字符組成,要驗證其中是否有任何字符是符號,您需要遍歷字符串中的每個字符並單獨驗證它們。 您可以使用Enumerable.Any
和char.IsSymbol
作為
string madeUppw = Console.ReadLine();
Console.WriteLine(madeUppw.Any(x=>char.IsSymbol(x)));
Enumerable.Any
驗證序列中的任何元素(在此字符串中)是否存在或滿足條件(在此,條件是任何字符是否為符號)。
最后一行可以進一步修剪為
Console.WriteLine(madeUppw.Any(char.IsSymbol));
如果需要打印字符串中的所有符號,可以使用
Console.WriteLine(string.Join(",",madeUppw.Where(x=>char.IsSymbol(x))));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.