统计字符串中某些字符的个数
时间: 1ms 内存:128M
描述:
编写一个实例方法getCount方法。该方法参数有三个,第一个参数可以是字符串s;第二个参数为输出参数,返回字符串s中字母个数;第三个参数也为输出参数,返回字符串s中数字个数
输入:
一个字符串s
输出:
该字符串中字母的个数,以及数字的个数
示例输入:
sfdh3dsfgjk4jfs7@
示例输出:
13
2
提示:
参考答案(内存最优[4348]):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{ int letter=0;
int integ=0;
string str = Console.ReadLine();
foreach (char myChar in str)
{
//Console.Write("{0}",myChar);
if(myChar>='A'&&myChar<='z'){
letter++;
}else if(myChar>='0'&&myChar<='9'){
integ++;
}
}
Console.WriteLine(letter);
Console.WriteLine(integ);
//Console.ReadKey();
}
}
}
参考答案(时间最优[26]):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();
Program pro = new Program();
pro.getCountChar(str);
//Console.ReadKey();
}
public void getCountChar(String s)
{
int cn = 0, nn = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] >= '0' && s[i] <= '9')
{
nn++;
}
if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z'))
{
cn++;
}
}
Console.WriteLine(cn);
Console.WriteLine(nn);
}
}
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。