在C#中,输入一个单词,怎么知道它有多少位字母
3个回答
展开全部
class Program//该程序不完整,你只需少加修改
{
static int num=0;
static void Main(string[] args)
{
Console.WriteLine("请输入一串字符:");
string str = Console.ReadLine();
new Program().GetWordsCount(str);
Console.WriteLine(num+1);
Console.ReadKey();
}
private void GetWordsCount(string str)
{
//空格标点符号,数字
for (int i = 0; i < str.Length; i++)
{
string obj = str[i].ToString();
if (IsNumber(obj) || obj == " " || IsPunctuation(obj))
{
num++;
GetWordsCount(str.Substring(i+1));
}
}
}
//判断是否是数字
private bool IsNumber(string num)
{
bool resu=true ;
try
{
int n = Convert.ToInt32(num);
}
catch (Exception)
{
resu = false;
}
return resu;
}
//判断是否是标点符号
private bool IsPunctuation(string s)
{
bool resu = false;
string charlist = ",。?!";
if (charlist.Contains(s))
{
resu = true;
}
return resu;
}
}
{
static int num=0;
static void Main(string[] args)
{
Console.WriteLine("请输入一串字符:");
string str = Console.ReadLine();
new Program().GetWordsCount(str);
Console.WriteLine(num+1);
Console.ReadKey();
}
private void GetWordsCount(string str)
{
//空格标点符号,数字
for (int i = 0; i < str.Length; i++)
{
string obj = str[i].ToString();
if (IsNumber(obj) || obj == " " || IsPunctuation(obj))
{
num++;
GetWordsCount(str.Substring(i+1));
}
}
}
//判断是否是数字
private bool IsNumber(string num)
{
bool resu=true ;
try
{
int n = Convert.ToInt32(num);
}
catch (Exception)
{
resu = false;
}
return resu;
}
//判断是否是标点符号
private bool IsPunctuation(string s)
{
bool resu = false;
string charlist = ",。?!";
if (charlist.Contains(s))
{
resu = true;
}
return resu;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询