一、字符串大小写转换
例题:将小写转换为大写用ToUpper方法,大写转换为小写用ToLower方法。
Console.WriteLine("请输入用户名!");
string name= Console.ReadLine();
string newname= input.ToLower();//将用户误输入的大写字母转换为小写
Console.WriteLine("请输入密码!");
string pass= Console.ReadLine();
if(newname=="admin")
Console.WriteLine("登陆成功!");
二、除去空格
例题:除去空格用Trim方法。
Console.WriteLine("请输入用户名!");
string name= Console.ReadLine();
string newname= input.ToLower();//将用户误输入的大写字母转换为小写
newname=newname.Trim();//除去用户误输入在前后的空格
Console.WriteLine("请输入密码!");
string pass= Console.ReadLine();
if(newname=="admin")
Console.WriteLine("登陆成功!");
在编写登陆页面是对用户名的一些处理是很重要的。
三、Trim方法的其它用处:可以除去一串字符串中位于前后的字符
例题:
Console.WriteLine("请输入");
string input = Console.ReadLine();
char[] strs=new char[2]{'s','h'};
//params关键字起到的作用:可以讲所有字符放在一个数组里作为trim方法的参数,也可以罗列所有要删除的字符,用逗号隔开
input = input.Trim('s','h','o');//与下一行效果相同
//input = input.Trim(strs);
Console.WriteLine(input);
如果输入hysou,结果如下
四、将字符串分割用Split方法
string str = "This is a sunny day";
string[] strs= str.Split(' ');//将字符串以空格截取成字符串数组
str = "";
for (int i = 0; i < strs.Length; i++)
{
str =str+ "\""+strs[i]+"\"";//转义字符
}
Console.WriteLine(str);
五、C#中的循环语句
do....while循环
例题:
do....while循环:无论while()中的条件是否为真,do{}中的代码都会预先执行一遍
int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i>=10);
while循环是当....则...
例题:
int i = 1;
while (i<=10)
{
Console.WriteLine(i);
i++;
}
switch循环语句
例题:
Console.WriteLine("输入0-2任意数字");
string num = Console.ReadLine();
switch (num)
{
case "0": Console.WriteLine("呵呵");
break;
case "1": Console.WriteLine("不错");
break;
default: Console.WriteLine("别再输入了!");
break;
}
for循环可以进行嵌套
例题:九九乘法表
static void Main(string[] args)
{
for (int i = 1; i < 10; i++)
{
for (int j = 1; j <=i; j++)//对于嵌套循环要找出第二个变量与第一个变量之间的关系
{
Console.Write("{0}*{1}={2} ",i,j,i*j);
}
Console.Write("\n");
}
未能找出第二个变量与第一个变量之间的关系
for (int i = 1; i < 10; i++)
{
for (int j = 1; j < 10; j++)
{
Console.Write("{0}*{1}={2} ", j, i, i * j);
if (i == j)
{
Console.WriteLine();
break;
}
}
}
百钱百鸡例题:
一只公鸡5元一只,母鸡3元一只,小鸡1元3只,100元买100只鸡,一共有几种买法。
根据数学思维可以设可以买公鸡x只,母鸡y只,小鸡z只.可列出 x+y+z=100和 5x+3y+z/3=100两个方程式。如果只买公鸡最多可买20只,同理母鸡最多可买33只。小鸡的数量有公鸡和母鸡的数量来控制。从而可以编码。
static void Main(string[] args)
{
double x, y, z,f=0;
for (x = 0; x <= 20; x++)
{
for (y = 0; y <= 33; y++)
{
z = 100 - x - y;
if(x*5+y*3+z/3==100)//如果x,y,z是int类型必须加&&z%3==0因为在计算机中4/3=1)
{
Console.WriteLine("可以买公鸡{0},买母鸡{1},买小鸡{2}",x,y,z);
f++;
}
}
}
Console.WriteLine("共有{0}种情况", f);
}
另一种方法
double x, y, z;
for (x = 0; x < 100; x++)
{
for (y = 0; y < 100; y++)
{
for (z = 0; z < 100; z++)
{
if (x * 5 + y * 3 + z / 3 == 100 && x + y + z == 100)//如果x,y,z是int类型&&z%3==0)
{
Console.WriteLine("可以买公鸡{0},买母鸡{1},买小鸡{2}", x, y, z);
}
}
}
}