常见字符串的方法
1.Format()函数对内容进行格式化。
String str = "Hello World!";
String name = "陈晨";
int age = 18;
String message = "大家好,我是{0},我今年{1}岁";
Console.WriteLine(string.Format(message,name,age));
注意该方法传入参数的个数要与占位符的个数和顺序一致。
2.IsNullOrEmpty是对传入的字符串判断是否为null或者空的即”“而IsNullOrWhiteSpace比前者作用更大,它可以判断传入的字符串是否是空格。
string username = null;
string password = "123456";
if(string.IsNullOrEmpty(username))
{
throw new ArgumentNullException("username is null");
}
else
{
if(string.IsNullOrEmpty(password))
{
throw new ArgumentNullException("password is null");
}
}
Console.WriteLine("username登录成功")
string username2 = " "
string password2 = "123456";
if(string.IsNullOrWhiteSpace(username2))
{
throw new ArgumentNullException("username2 is 空格");
}
else
{
if(string.IsNullOrWhiteSpace(password2))
{
throw new ArgumentNullException("password2 is null");
}
}
Console.WriteLine("username2登录成功")
上述代码模拟了登录的流程,判断用户输入的账号密码是否为null或者”“,而要判断用户输入的字符串是否为空格时则必须使用IsNullOrWhiteSpace方法。
3.equals方法是判断是否相等。
using DJConsoleProject;
hello hello=new hello();
hello hello2 = new hello();
if(hello.Equals(hello2))
{
Console.WriteLine("相等");
}
else
{
Console.WriteLine("不相等");
}
最终程序运行的结果是不相等。
4.Contains判断字符串中是否有传入的参数。
string str = "Hello World.";

最低0.47元/天 解锁文章
6886

被折叠的 条评论
为什么被折叠?



