024集—— 正则表达式、replace、DateTime日期的用法——C#学习笔记
DateTime 是一个struct结构体。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
args = new string[] { "yngqq","qq" };
// To run this program, provide a command line string.
// In Visual Studio, see Project > Properties > Debug.
string userName = args[0];
string date = DateTime.Now.ToString (); //Today.ToShortDateString();
// Use the + and += operators for one-time concatenations.
string str = "你好," + userName + ",现在是 " + date + "。";
System.Console.WriteLine(str);
str += " 你好吗?";
System.Console.WriteLine(str);
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
以下是正则表达式及replace的用法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class ReplaceSubstrings
{
string searchFor;
string replaceWith;
static void Main(string[] args)
{
ReplaceSubstrings app = new ReplaceSubstrings();
string s = "齐天大圣 孙悟空 到此一游!哈哈";
Console.WriteLine(s);
// Replace one substring with another with String.Replace.
// Only exact matches are supported.
s = s.Replace("孙悟空", "孙行者");
Console.WriteLine(s);
// Output: The peaks are behind the clouds today.
// Use Regex.Replace for more flexibility.
// Replace "the" or "The" with "many" or "Many".
// using System.Text.RegularExpressions
app.searchFor = "齐天大圣"; //一个简单的正则表达式.
app.replaceWith = "美猴王";
s = Regex.Replace(s, app.searchFor, app.ReplaceMatchCase, RegexOptions.IgnoreCase);
Console.WriteLine(s);
// Output: Many peaks are behind many clouds today.
// Replace all occurrences of one char with another.
s = s.Replace(' ', '_');
Console.WriteLine(s);
s = s.Replace("!", "");
Console.WriteLine(s);
// Output: Many_peaks_are_behind_many_clouds_today.
// Remove a substring from the middle of the string.
string temp = "一游";
int i = s.IndexOf(temp);
if (i >= 0)
{
s = s.Remove(i, temp.Length);
}
Console.WriteLine(s);
// Output: Many_peaks_are_behind_clouds_today.
// Remove trailing and leading whitespace.
// See also the TrimStart and TrimEnd methods.
string s2 = " 二师兄,我来了 ";
// Store the results in a new string variable.
temp = s2.Trim();
Console.WriteLine(temp);
// Output: I'm wider than I need to be.
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// Custom match method called by Regex.Replace
// using System.Text.RegularExpressions
string ReplaceMatchCase(Match m)
{
// Test whether the match is capitalized
if (Char.IsUpper(m.Value[0]) == true)
{
// Capitalize the replacement string
// using System.Text;
StringBuilder sb = new StringBuilder(replaceWith);
sb[0] = (Char.ToUpper(sb[0]));
return sb.ToString();
}
else
{
return replaceWith;
}
}
}
}