位运算
一个int占用4个字节,一个字节包含8位。
int a = 60; //0011 1100
int b = 13; //0000 1101
// & 0000 1100
// | 0011 1101
// ^ 0011 0001
Console.WriteLine(Convert.ToString(~a, 2));
// 1111 1111 1111 1111 1111 1111 1100 0011 -61补码
Console.WriteLine(Convert.ToString(b>>2,2));
// 0000 0011
可空类型 Nullable
? 单问号用于对 int、double、bool 等无法直接赋值为 null 的数据类型进行 null 的赋值,意思是这个数据类型是 Nullable 类型的。
- 可空类型允许将值类型变量的值设置为 Null,并可以通过 HasValue 属性判断其是否为 Null 值。
int? i; //默认值null
int i;//默认值0
?? 合并运算符
int? num1 = null;
Console.WriteLine(num1 ?? 3); //3
int? num2 = 5;
Console.WriteLine(num2 ?? 8); //5
字符串
string test1 = "abcdefg";
// Length 获取字符串的长度,即字符串中字符的个数
for (int i = test1.Length - 1; i >= 0; i--)
{
Console.WriteLine(test1[i]);
}
// IndexOf和LastIndexOf:查找字符串中的字符 返回位置,返回-1 未找到
int firstIndex = test1.IndexOf("cd");
int lastIndex = test1.LastIndexOf("cd");
if (firstIndex != -1)
{
if (firstIndex == lastIndex)
{
Console.WriteLine("只有一个cd");
}
}
//Contains:包含字符串
string str = "This is test";\
if (str.Contains("test"))
// Replace:字符串替换函 没有就什么都不发生
test1 = test1.Replace("ce", "-tihuan-");
Console.WriteLine(test1);
// Substring:字符串截取函数
string test2;
test2 = test1.Substring(0, firstIndex);
Console.WriteLine(test2);
// Insert:字符串插入
string test3 = test1.Insert(1, "A");
Console.WriteLine(test3);
// Compare: 字符串是否相等
if (String.Compare(str1, str2) == 0)
switch case
switch (point) //表达式 point 的结果必须是整型、字符串类型、字符型、布尔型等数据类型。
{
case 10:
case 9:
Console.WriteLine(9);
break;
}
循环
// for
for (int i = 1; i < 10; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("{0}*{1}={2}\t", i, j, i * j);
}
Console.WriteLine();
}
Console.ReadKey();
// foreach
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
Console.WriteLine(element);
}
// while
while(true)
{
Console.WriteLine("一直在循环");
}
// do while
do
{
Console.WriteLine("至少会走一次");
} while (false);
// break 停止最内层的循环
// continue 强迫开始下一次循环
goto
由于 goto 语句不便于程序的理解,因此 goto 语句并不常用。
class Program
{
static void Main(string[] args)
{
int count = 1;
login:
Console.WriteLine("请输入用户名");
string username = Console.ReadLine();
Console.WriteLine("请输入密码");
string userpwd = Console.ReadLine();
if (username == "aaa" && userpwd == "123")
{
Console.WriteLine("登录成功");
}
else
{
count++;
if (count > 3)
{
Console.WriteLine("用户名或密码错误次数过多!退出!");
}
else
{
Console.WriteLine("用户名或密码错误");
goto login;//返回login标签处重新输入用户名密码
}
}
}
}