C#字符串处理和时间格式化整理

1、字符串截取

string str = "123abc456";

str = str.Substring(0, 4);           //取前面几个字符 123a

str = str.Substring(3);            //从第几个位置取后面字符 abc456

2、替换指定字符串

string str = "123abc456";

3、查看字符串中是否包含字符

string str = "我爱北京天安门";

int index = str.IndexOf("爱");

if (index > -1)

{

  Console.Write("找到了");           //找到了

}

else

{

  Console.Write("未找到");

}

-----------------------------------------------------------------------------------------------------------

string str = "我爱北京天安门";

if (str.Contains("爱"))

{

  Console.Write("找到了"); //找到了

}

else

{

  Console.Write("未找到");

}

4、字符串长度

string str = "123abc456";

int num = str.Length //9

5、根据特定字符分割成数组

string str="aaa,bbb,ccc";

string[] sArray=str.Split(',');

foreach (string i in sArray)

{

  Console.Write(i.ToString() + " ");        //aaa bbb ccc

}

6、判断变量是否为空

string str="";

if (string.IsNullOrWhiteSpace(str))

{

  Console.Write("空");            // “”或“ ”或null 都是空

}

else

{

  Console.Write("不空");

}

---------------------------------------------------------------------------------------

string.IsNullOrEmpty(str)            //// 不存在或null 都是空

二、PHP日期格式

1、时间格式化

C#字符串处理和时间格式化整理

Console.Write(DateTime.Now.Date.ToShortDateString());           //当前年月日 2018/11/27

Console.Write(DateTime.Now.Date.AddDays(-1).ToShortDateString());     //昨天年月日 2018/11/26

Console.Write(DateTime.Now);                     //当前时间 2018/11/27 09:14:15

Console.Write(DateTime.Now.Hour);                   //当前小时 11

Console.Write(DateTime.Now.AddYears(1));               //当前时间 2018/11/27 09:14:15