C#-string,StringBuilder和Regex类的讲解
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-CN" />
<title> new document </title>
<meta name="generator" content="editplus" />
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<style type="text/css">
/*<![CDATA[*/
* { width:100%; margin:0; padding:0;}
body { font-family: "宋体", Arial, Helvetica, sans-serif; font-size: 12px; color: #444; text-align:center;}
ul { list-style-type: none; margin:0; padding:0;}
a { color:#4e4e4e; text-decoration: none; vertical-align: middle;}
a:hover {color: #990000;}
a:visited {color: #4e4e4e;}
#login {width:186px;height:100px; border: 1px solid #d2d2d2; margin:100px auto;}
#login .top {margin-top:6px; margin-left:6px; width:60px; float:left;background:url(http://www.lanrentuku.com/images/uppic/200812291724020.gif) no-repeat -100px 6px; height:24px;}
#login h2 { font-size:12px; line-height:26px;text-align:left;text-indent: 21px;}
#moveico { margin-top:8px; background:url(http://www.lanrentuku.com/images/uppic/200812291724020.gif) no-repeat 12px -30px; width:110px; height:24px; float:left;}
#moveico div {position: relative;float:left;left:13px; top:4px;background:url(http://www.lanrentuku.com/images/uppic/200812291724020.gif) no-repeat -80px 0; width:12px; height:12px;}
#login input { height:16px; color:#666;}
#login .userchk { width:16px;}
#login .userinput { width:92px; border:1px #cbdca8 solid;}
#login .usersub { width:52px;height:18px; background:url(http://www.lanrentuku.com/images/uppic/200812291724020.gif) no-repeat; border:0; line-height:22px; color:#454545; font-size:12px;}
#login span { margin-left:8px;}
#login ul {width:160px;margin:0 auto;}
#login li { clear:left; height:21px; line-height:21px; text-align:left;overflow:hidden;}
#login li.other {border-top:2px #e0ecc8 solid; margin-top:3px;text-indent: 6px;}
#login a#loginhelp {position: relative; top:-18px;left:145px;display:block; width:12px; height:12px; background:#f7fcfc url(http://www.lanrentuku.com/images/uppic/200812291724020.gif) no-repeat -60px 0; }
/*]]>*/
</style>
<script type="text/javascript">
<!--
//Moveobj
function bind(o,ev,fn){
if (document.all)o.attachEvent('on'+ev,fn);
else o.addEventListener(ev,fn,false);
}
function setCookie(name,value,time){
var exp = new Date();
exp.setTime(exp.getTime() + 30*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name){
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg)) return unescape(arr[2]);
else return null;
}
function Move_autosetdef(moveobj){
var logintit = new Array("学生","家长","老师","管理员");
var bNum =13 ,mNum =22 , iNum = 4 , icolength = 6;
//分别 bNum 起始距离距moveobj内侧左部的长度 ,mNum 单位长度,iNum 单位数 0-1-2-3,icolength 图标距离的1/2。
var eNum = bNum + mNum * (iNum-1);
var $D = new Function('str','return document.getElementById(str);');
var $event = new Function('e','return (!e)?window.event:e;');
var checknowleft = function(z){return ((z<bNum)?bNum:((z>eNum)?eNum:(((z-bNum)%mNum>11)?z+mNum-(z-bNum)%mNum:z-(z-bNum)%mNum)));}
var nowseat = 0,drag_=false;
var Move_autoset = function(iNum){
$D(moveobj).getElementsByTagName("div")[0].style.left = iNum*mNum+bNum+"px";
$D("login-tit").innerHTML = logintit[iNum];
$D("login-type").value = iNum;//向hidden的login-type里添加参数值
}
nowseat = (getCookie("nowseat")==null)?0:getCookie("nowseat");
Move_autoset(nowseat);
$D(moveobj).getElementsByTagName("div")[0].onmouseover = function(){
var x,y,z;
this.onmousedown=function(e){
drag_=true;
with(this){
var temp0=style.left.replace("px","")*1,temp1=offsetLeft,temp2=offsetTop;
x=$event(e).clientX;
y=$event(e).clientY;
z=temp0;
document.onmousemove=function(e){
//this.selection.empty();
if(!drag_)return false;
with(this){
z = temp0 + $event(e).clientX-x;
z = (z<bNum)?bNum:((z>eNum)?eNum:z);
style.left=z+"px";
}
}
document.onmouseup=function(e){
drag_ = false;
var nowleft = checknowleft(z);
nowseat = (nowleft-bNum)/mNum;
Move_autoset(nowseat);
setCookie('nowseat',(nowleft-bNum)/mNum);
}
}
}
}
$D(moveobj).onmouseover = function(){
this.onmousedown=function(e){
if(drag_)return false;
with(this){
var icoobj = getElementsByTagName("div")[0];
var temp0 = icoobj.offsetLeft;
var x=$event(e).clientX;
var nowleft = checknowleft(bNum+mNum*nowseat+(x-temp0)-icolength);
document.onmouseup=function(e){
nowseat = (nowleft-bNum)/mNum;
Move_autoset(nowseat);
setCookie('nowseat',(nowleft-bNum)/mNum);
}
}
}
}
}
bind(window,"load",new Function('Move_autosetdef("moveico")'));
//-->
</script>
</head>
<body>
<div id="login" class="Box">
<form action="" method="post">
<div id="moveico"><div></div></div>
<div class="top"><h2 class="active" id="login-tit"></h2></div>
<input type="hidden" id="login-type" name="stype" value="0" />
<ul>
<li> <input name="" type="text" class="userinput" /><span><label for="isRemember"> <input name="isRemember" id="isRemember" type="checkbox" value="" class="userchk" /> 记住</label></span></li>
<li> <input name="" type="password" class="userinput" /><span><input name="" type="submit" value="登 陆" class="usersub"/></span></li>
<li class="other"><a href="#3">忘记密码</a> | <a href="#3">注册/通行证</a><a href="#3" id="loginhelp"></a></li>
</ul>
</form>
</div>
<br/>
</body>
</html>
using System;
using System.Text;
namespace SetPassword
{
/// <summary>
/// .net 密码加密
/// </summary>
class CbsPassword
{
[STAThread]
static void Main(string[] args)
{
string pwd = "hello你好啊";
Console.WriteLine("原字符串:" + pwd + "," + pwd.Length.ToString());
Console.WriteLine("字符串加密:" + StringEncoding(pwd) + "," + StringEncoding(pwd).Length.ToString());
Console.WriteLine("字符串解密:" + StringDecoding(StringEncoding(pwd)) + "," + StringDecoding(StringEncoding(pwd)).Length.ToString());
Console.ReadLine();
}
static string StringEncoding(string pwd)
{
char [] arrChar = pwd.ToCharArray();
string strChar = "";
for(int i = 0;i < arrChar.Length;i++)
{
arrChar[i] = Convert.ToChar(arrChar[i]+1);
strChar = strChar + arrChar[i].ToString();
}
return strChar;
}
static string StringDecoding(string pwd)
{
char [] arrChar = pwd.ToCharArray();
string strChar = "";
for(int i = 0;i < arrChar.Length;i++)
{
arrChar[i] = Convert.ToChar(arrChar[i]-1);
strChar = strChar + arrChar[i].ToString();
}
return strChar;
}
}
}
字符串的声明与初始化以及获得字符串的长度范例
范例一
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string string1;//声明一个名称为string1的字符串
string1="I Love C#";//对string1进行赋值为"I Love C#",注意不要忘记 "" 符号
Console.WriteLine("string1={0}",string1);
Console.WriteLine("string1的长度为{0}",string1.Length);
string string2="I Love C#";//声明一个名称为string2的字符串并且赋值为"I Love C#"
Console.WriteLine("string2={0}",string2);
Console.WriteLine("string2的长度为{0}",string2.Length);
}
}
}
运行结果
string1=I Love C#
string1的长度为9
string2=I Love C#
string2的长度为9
Press any key to continue
2:利用“+”运算符将两个字符串或者多个字符串相连接以及Concat()方法的用法
范例一
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string string1;//声明一个名称为string1的字符串
string1="I Love C#";//对string1进行赋值为"I Love C#",注意不要忘记 "" 符号
Console.WriteLine("string1={0}",string1);
string string2="I Love Java";//声明一个名称为string2的字符串并且赋值为"I Love C#"
Console.WriteLine("string2={0}",string2);
Console.WriteLine("运用+运算符将string1和string2进行连接:");
string string3=string1+" "+string2;
Console.WriteLine("string3={0}",string3);
}
}
}
运行结果
string1=I Love C#
string2=I Love Java
运用+运算符将string1和string2进行连接:
string3=I Love C# I Love Java
Press any key to continue
范例二:方法Concat()的用法
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str1="hello java";
string str2="hello world";
Console.WriteLine("使用方法Concat()将str1和str2相连后内容为-->{0}",string.Concat(str1," && ",str2));
}
}
}
运行结果为:
使用方法Concat()将str1和str2相连后内容为-->hello java && hello world
Press any key to continue
字符串的比较与运算符范例
范例一
在下面的范例中需要我们掌握的方法有
1:Compare(string str1,string str2,bool b)如果b为true则在比较的时候忽略大小写,反之为false
2:Compare(string str1,string str2)
3:CompareTo()
4:StartsWith()
5:EndsWith()
6:IndexOf()
7:LastIndexOf()
对于上面的这些方法在下面的范例中可以看出其各自的用法。请看范例
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str1="I Love C#";
string str2="I Love c#";
string str3="I Love Java";
Console.WriteLine("str1是否等于str2:-->{0}",string.Compare(str1,str2));
Console.WriteLine("str1在忽略大小写的情况下是否等于str2-->{0}",string.Compare(str1,str2,true));
Console.WriteLine("str1是否等于str3-->{0}",str1.CompareTo(str3));
Console.WriteLine("str1的第0个字符是否与str3的第0个字符相等-->{0}",string.Compare(str1,0,str2,0,2));
Console.WriteLine("str1的第7个字符是否与str3的第7个字符相等-->{0}",string.Compare(str1,7,str2,7,2));
Console.WriteLine("str1的第7个字符是否与str3的第7个字符在忽略大小写的情况下相等-->{0}",string.Compare(str1,7,str2,7,2,true));
Console.WriteLine("str1是否以字符'I'开头-->{0}",str1.StartsWith("I"));
Console.WriteLine("str1是否以字符'i'开头-->{0}",str1.StartsWith("i"));
Console.WriteLine("str2是否以c# 结尾-->{0}",str2.EndsWith("c#"));
Console.WriteLine("字符串‘L’为字符串{0}第{1}个字符:",str3,str3.IndexOf('L'));
Console.WriteLine("字符'L'在字符串{0}中最后出现的位置为{1}",str3,str3.LastIndexOf('L'));
}
}
}
运行结果
str1是否等于str2:-->1
str1在忽略大小写的情况下是否等于str2-->0
str1是否等于str3-->-1
str1的第0个字符是否与str3的第0个字符相等-->0
str1的第7个字符是否与str3的第7个字符相等-->1
str1的第7个字符是否与str3的第7个字符在忽略大小写的情况下相等-->0
str1是否以字符'I'开头-->True
str1是否以字符'i'开头-->False
str2是否以c# 结尾-->True
字符串‘L’为字符串I Love Java第2个字符:
字符'L'在字符串I Love Java中最后出现的位置为2
Press any key to continue
字符串的分割与获取
String类提供了一个方法Split用以切割字符串,此方法返回一个包含所有分割子字符串的数组对象,可以经过数组取得所有分割的子字符串。请看下面的范例
范例一
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str="How are you:what's you name:I love java";
string result="";
char split=':';
foreach(string s in str.Split(split)){
result+=s+'\n';
}
Console.WriteLine(result);
}
}
}
运行结果
How are you
what's you name
I love java
Press any key to continue
范例二
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str="How.are you:what's. you name:I. love java";
string result="";
char [] split=new char[] {':','.'};
foreach(string s in str.Split(split)){
result+=s+'\n';
}
Console.WriteLine(result);
}
}
}
运行结果
How
are you
what's
you name
I
love java
Press any key to continue
方法Equals()和"=="的用法
范例一
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str1="hello java";
string str2="hello java";
Console.WriteLine("str1.Equals(str2)-->{0}",str1.Equals(str2));
Console.WriteLine("str1==str2-->{0}",(str1==str2));
}
}
}
运行结果
str1.Equals(str2)-->True
str1==str2-->True
Press any key to continue
获取字符串范例
String类提供了Substring(int i)方法,获取变量i以后的子字符串,包括i本身。请看下面的范例
范例一:
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str="zhong hua ren min gong he guo";
Console.WriteLine("原始字符串为-->{0}",str);
Console.WriteLine("获取第6个字符以后的字符串为-->{0}",str.Substring(6));
}
}
}
运行结果
原始字符串为-->zhong hua ren min gong he guo
获取第6个字符以后的字符串为-->hua ren min gong he guo
Press any key to continue
字符的删除,插入,与大小写的转换
范例一:在下面的范例中需要我们掌握的方法如下
1:TrimStart()
2:TrimEnd()
3:Remove()
4:Insert()
5:PadLeft()
6:PadRight
7:ToUpper()
8:ToLower()
9:Trim()
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str1=" hello";
string str2="java ";
string str3=" hello java ";
Console.WriteLine("str1的原始字符串为{0}-->"+str1);
Console.WriteLine("使用TrimStart()方法将字符串{0}左边的空格删除后字符串为-->{1}",str1,str1.TrimStart());
Console.WriteLine("使用remove()方法删除第0个字符以后的3个字符后,str1的内容为-->{0}",str1.Remove(0,3));
Console.WriteLine("在str1的第6个字符中加入一个字符'*',后str1的内容为-->{0}",str1.Insert(6,"*"));
Console.WriteLine("在str1的左边加上二个‘+’符号后str1的内容为-->{0}",str1.PadLeft(8,'+'));
Console.WriteLine("在str1的右边加上二个‘+’符号后str1的内容为-->{0}",str1.PadRight(8,'+'));
Console.WriteLine("把str1的内容转换为大写后为-->{0}",str1.ToUpper());
Console.WriteLine("把str1的内容转换为小写后为-->{0}",str1.ToLower());
Console.WriteLine("_________________________________________________________");
Console.WriteLine("str2的原始字符串为-->{0}",str2);
Console.WriteLine("使用TrimEnd()方法将字符串{0}右边的空格删除后字符串为-->{1}",str2,str2.TrimEnd());
Console.WriteLine("使用remove()方法删除第2个字符以后的2个字符后,str1的内容为-->{0}",str2.Remove(2,3));
Console.WriteLine("在str2的第4个字符中加入一个字符'*',后str2的内容为-->{0}",str2.Insert(4,"*"));
Console.WriteLine("在str2的左边加上二个‘+’符号后str2的内容为-->{0}",str2.PadLeft(7,'+'));
Console.WriteLine("在str2的右边加上二个‘+’符号后str2的内容为-->{0}",str2.PadRight(7,'+'));
Console.WriteLine("把str2的内容转换为大写后为-->{0}",str2.ToUpper());
Console.WriteLine("把str2的内容转换为小写后为-->{0}",str2.ToLower());
Console.WriteLine("_________________________________________________________");
Console.WriteLine("str3的原始字符串为-->{0}",str3);
Console.WriteLine("使用Trim()方法将字符串{0}两边的空格删除后字符串为-->{1}",str3,str3.Trim());
Console.WriteLine("使用remove()方法删除第6个字符以后的3个字符后,str1的内容为-->{0}",str3.Remove(6,5));
Console.WriteLine("在str3的第1个字符中加入一个字符'*',在第12个字符中插入‘*’后str3的内容为-->");
Console.WriteLine(str3.Insert(1,"*").Insert(12,"*"));
Console.WriteLine("在str3的左边加上二个‘+’符号后str3的内容为-->{0}",str3.PadLeft(14,'+'));
Console.WriteLine("在str3的右边加上二个‘+’符号后str3的内容为-->{0}",str3.PadRight(14,'+'));
Console.WriteLine("把str3的内容转换为大写后为-->{0}",str3.ToUpper());
Console.WriteLine("把str3的内容转换为小写后为-->{0}",str3.ToLower());
}
}
}
运行结果
在str1的第6个字符中加入一个字符'*',后str1的内容为--> hello*
在str1的左边加上二个‘+’符号后str1的内容为-->++ hello
在str1的右边加上二个‘+’符号后str1的内容为--> hello++
把str1的内容转换为大写后为--> HELLO
把str1的内容转换为小写后为--> hello
_________________________________________________________
str2的原始字符串为-->java
使用TrimEnd()方法将字符串java 右边的空格删除后字符串为-->java
使用remove()方法删除第2个字符以后的2个字符后,str1的内容为-->ja
在str2的第4个字符中加入一个字符'*',后str2的内容为-->java*
在str2的左边加上二个‘+’符号后str2的内容为-->++java
在str2的右边加上二个‘+’符号后str2的内容为-->java ++
把str2的内容转换为大写后为-->JAVA
把str2的内容转换为小写后为-->java
_________________________________________________________
str3的原始字符串为--> hello java
使用Trim()方法将字符串 hello java 两边的空格删除后字符串为-->hello java
使用remove()方法删除第6个字符以后的3个字符后,str1的内容为--> hello
在str3的第1个字符中加入一个字符'*',在第12个字符中插入‘*’后str3的内容为-->
*hello java*
在str3的左边加上二个‘+’符号后str3的内容为-->++ hello java
在str3的右边加上二个‘+’符号后str3的内容为--> hello java ++
把str3的内容转换为大写后为--> HELLO JAVA
把str3的内容转换为小写后为--> hello java
Press any key to continue
Join()方法的用法范例
范例一:
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string [] str1={"I","am","a","student"};
Console.WriteLine("str1的原始内容为:");
for(int i=0;i<str1.Length;i++){
Console.Write(str1[i]+" ");
}
Console.WriteLine("\n以下是使用Join方法后输出的str1的内容:");
Console.WriteLine(string.Join(".",str1));
}
}
}
运行结果为
str1的原始内容为:
I am a student
以下是使用Join方法后输出的str1的内容:
I.am.a.student
Press any key to continue
Clone()方法的使用范例
范例一
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str1="hello world";
Console.WriteLine("str1-->{0}",str1);
Console.WriteLine("使用Clone()方法创建一个和str1相同的字符串str2");
string str2=(string)str1.Clone();
Console.WriteLine("str2-->{0}",str2);
}
}
}
运行结果
str1-->hello world
使用Clone()方法创建一个和str1相同的字符串str2
str2-->hello world
Press any key to continue
CopyTo()方法的用法范例
范例一
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str1="hello world";
char [] array=new char[str1.Length];
str1.CopyTo(0,array,0,str1.Length);
Console.WriteLine(str1);
}
}
}
StringBuilder类的用法范例
StringBuilder可以根据情况动态的调整大小,对于其它的我们在这里就不多说了,但是必须记住如果我们要使用StringBuilder,必须将using System.Text导出。下面请看一个 范例,如果掌握了这个范例里出现的方法,那么对于StringBuilder我们也就可以说能运用自如了。
范例一:
在这个范例中出现的方法为
1:Capacity
2:Length
3:Append()
4:Replace()
5:Insert()
6:Remove()
using System;
using System.Text;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
StringBuilder sb1=new StringBuilder();
Console.WriteLine("sb1的初始容量为:-->{0}",sb1.Capacity);
Console.WriteLine("sb1的初始长度为:-->{0}",sb1.Length);
sb1.Append("hello world");
Console.WriteLine("向sb1中添加后sb1的容量为:-->{0}",sb1.Capacity);
Console.WriteLine("向sb1中添加后sb1的长度为:-->{0}",sb1.Length);
sb1.Append(" hello C# zhong hua ren min gong he guo ");
Console.WriteLine("在次向sb1中添加后sb1的容量为:-->{0}",sb1.Capacity);
Console.WriteLine("在次向sb1中添加后sb1的长度为:-->{0}",sb1.Length);
StringBuilder sb2=new StringBuilder("I Love java",30);
Console.WriteLine("the original text of sb2 are:");
Console.WriteLine(sb2);
Console.WriteLine("使用replace方法将sb2中的java换成C#后内容为:");
Console.WriteLine(sb2.Replace("java","C#"));
Console.WriteLine("使用insert方法在sb2第七个字符中添加'java and '后sb2的内容为");
Console.WriteLine(sb2.Insert(7,"java and "));
Console.WriteLine("使用remove方法将sb2中第0个字符以后的6删除后sb2的内容为:");
Console.WriteLine(sb2.Remove(0,7));
}
}
}
运行结果
sb1的初始容量为:-->16
sb1的初始长度为:-->0
向sb1中添加后sb1的容量为:-->16
向sb1中添加后sb1的长度为:-->11
在次向sb1中添加后sb1的容量为:-->52
在次向sb1中添加后sb1的长度为:-->51
the original text of sb2 are:
I Love java
使用replace方法将sb2中的java换成C#后内容为:
I Love C#
使用insert方法在sb2第七个字符中添加'java and '后sb2的内容为
I Love java and C#
使用remove方法将sb2中第0个字符以后的6删除后sb2的内容为:
java and C#
Press any key to continue
正则表达式的用法范例
在使用正则表达式之前必须将using System.Text.RegularExpressions导出。下面我们就来通过范例来了解一下正则表达式的使用方法。
范例一
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string test="aklsfhkasjlhasdasdfhjkalsfhkljasljkdfhkljasfdjkhasjk";
string match;
int count=0;
while(true){
Console.WriteLine("原始字符串为-->{0}",test);
Console.WriteLine("请输入要查找的字符");
match=Console.ReadLine();
Regex myregex=new Regex(@match);
MatchCollection mcl=myregex.Matches(test);
foreach(Match mymatch in mcl){
Console.WriteLine("{0}在第{1}个字符被发现!!",mymatch,mymatch.Index);
count++;
}
Console.WriteLine("{0}出现了{1}次",match,count);
count=0;
}
}
}
}
运行结果
原始字符串为-->aklsfhkasjlhasdasdfhjkalsfhkljasljkdfhkljasfdjkhasjk
请输入要查找的字符
a
a在第0个字符被发现!!
a在第7个字符被发现!!
a在第12个字符被发现!!
a在第15个字符被发现!!
a在第22个字符被发现!!
a在第30个字符被发现!!
a在第41个字符被发现!!
a在第48个字符被发现!!
a出现了8次
原始字符串为-->aklsfhkasjlhasdasdfhjkalsfhkljasljkdfhkljasfdjkhasjk
请输入要查找的字符
范例二
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string str1="use java to write. a program";
Regex r=new Regex(@"(\.)");
string []result=r.Split(str1);
foreach(string s in result){
Console.WriteLine(s);
}
result=Regex.Split(str1,@"(\.)");
foreach(string s in result){
Console.WriteLine(s);
}
}
}
}
运行结果
use java to write
.
a program
use java to write
.
a program
Press any key to continue
范例三
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
string test="java is a computer language,c# also is a computer language java is a poupular computer language";
Console.WriteLine("original text of test are:");
Console.WriteLine(test);
string str;
int count=0;
while(true){
Console.WriteLine("请输入你要查询的字符串 例如"+"java");
str=Console.ReadLine();
Regex r=new Regex(str);
MatchCollection mcl=r.Matches(test);
foreach(Match mymatch in mcl){
Console.WriteLine("{0}在第{1}个位置出现",mymatch,mymatch.Index);
count++;
}
Console.WriteLine("{0}出现了{1}次",str,count);
count=0;
if(str.Equals("break")) break;
}
}
}
}
运行结果
original text of test are:
java is a computer language,c# also is a computer language java is a poupular co
mputer language
请输入你要查询的字符串 例如java
computer
computer在第10个位置出现
computer在第41个位置出现
computer在第78个位置出现
computer出现了3次
请输入你要查询的字符串 例如java
break
break出现了0次
Press any key to continue
日期时间的格式化
范例一
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
DateTime dt=DateTime.Now;
Console.WriteLine("格式 d:{0:d},格式 D:{1:D}",dt,dt);
Console.WriteLine("格式 t:{0:t},格式 T:{1:T}",dt,dt);
Console.WriteLine("格式 f:{0:f},格式 F:{1:T}",dt,dt);
Console.WriteLine("格式 g:{0:g},格式 G:{1:G}",dt,dt);
Console.WriteLine("格式 m:{0:m},格式 M:{1:M}",dt,dt);
}
}
}
运行结果
格式 d:2007-3-20,格式 D:2007年3月20日
格式 t:19:13,格式 T:19:13:42
格式 f:2007年3月20日 19:13,格式 F:19:13:42
格式 g:2007-3-20 19:13,格式 G:2007-3-20 19:13:42
格式 m:3月20日,格式 M:3月20日
Press any key to continue
toString()方法范例
范例一
using System;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
int a=20;
Console.WriteLine("a={0}",a);
Console.WriteLine("将a转换成string类型后a={0}",a.ToString());
double b=2.25;
Console.WriteLine("b={0}",b);
Console.WriteLine("将b转换成string类型后a={0}",b.ToString());
}
}
}
运行结果
a=20
将a转换成string类型后a=20
b=2.25
将b转换成string类型后a=2.25
Press any key to continue
C#格式化数值结果表
字符 |
说明 |
示例 |
输出 |
C | 货币 | string.Format("{0:C3}", 2) | $2.000 |
D | 十进制 | string.Format("{0:D3}", 2) | 002 |
E | 科学计数法 | 1.20E+001 | 1.20E+001 |
G | 常规 | string.Format("{0:G}", 2) | 2 |
N | 用分号隔开的数字 | string.Format("{0:N}", 250000) | 250,000.00 |
X | 十六进制 | string.Format("{0:X000}", 12) | C |
string.Format("{0:000.000}", 12.2) | 012.200 |
Strings
There really isn't any formatting within a strong, beyond it's alignment. Alignment works for any argument being printed in a String.Format call.
Sample | Generates |
String.Format("->{1,10}<-", "Hello"); | -> Hello<- |
String.Format("->{1,-10}<-", "Hello"); | ->Hello <- |
Numbers
Basic number formatting specifiers:
Specifier | Type | Format |
Output |
Output |
c | Currency | {0:c} | $1.42 | -$12,400 |
d | Decimal (Whole number) | {0:d} | System. FormatException |
-12400 |
e | Scientific | {0:e} | 1.420000e+000 | -1.240000e+004 |
f | Fixed point | {0:f} | 1.42 | -12400.00 |
g | General | {0:g} | 1.42 | -12400 |
n | Number with commas for thousands | {0:n} | 1.42 | -12,400 |
r | Round trippable | {0:r} | 1.42 | System. FormatException |
x | Hexadecimal | {0:x4} | System. FormatException |
cf90 |
Custom number formatting:
Specifier | Type | Example | Output (Passed Double 1500.42) | Note |
0 | Zero placeholder | {0:00.0000} | 1500.4200 | Pads with zeroes. |
# | Digit placeholder | {0:(#).##} | (1500).42 | |
. | Decimal point | {0:0.0} | 1500.4 | |
, | Thousand separator | {0:0,0} | 1,500 | Must be between two zeroes. |
,. | Number scaling | {0:0,.} | 2 | Comma adjacent to Period scales by 1000. |
% | Percent | {0:0%} | 150042% | Multiplies by 100, adds % sign. |
e | Exponent placeholder | {0:00e+0} | 15e+2 | Many exponent formats available. |
; | Group separator | see below |
The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:
Dates
Note that date formatting is especially dependant on the system's regional settings; the example strings here are from my local locale.
Specifier | Type | Example (Passed System.DateTime.Now) |
d | Short date | 10/12/2002 |
D | Long date | December 10, 2002 |
t | Short time | 10:11 PM |
T | Long time | 10:11:29 PM |
f | Full date & time | December 10, 2002 10:11 PM |
F | Full date & time (long) | December 10, 2002 10:11:29 PM |
g | Default date & time | 10/12/2002 10:11 PM |
G | Default date & time (long) | 10/12/2002 10:11:29 PM |
M | Month day pattern | December 10 |
r | RFC1123 date string | Tue, 10 Dec 2002 22:11:29 GMT |
s | Sortable date string | 2002-12-10T22:11:29 |
u | Universal sortable, local time | 2002-12-10 22:13:50Z |
U | Universal sortable, GMT | December 11, 2002 3:13:50 AM |
Y | Year month pattern | December, 2002 |
The 'U' specifier seems broken; that string certainly isn't sortable.
Custom date formatting:
Specifier | Type | Example | Example Output |
dd | Day | {0:dd} | 10 |
ddd | Day name | {0:ddd} | Tue |
dddd | Full day name | {0:dddd} | Tuesday |
f, ff, ... | Second fractions | {0:fff} | 932 |
gg, ... | Era | {0:gg} | A.D. |
hh | 2 digit hour | {0:hh} | 10 |
HH | 2 digit hour, 24hr format | {0:HH} | 22 |
mm | Minute 00-59 | {0:mm} | 38 |
MM | Month 01-12 | {0:MM} | 12 |
MMM | Month abbreviation | {0:MMM} | Dec |
MMMM | Full month name | {0:MMMM} | December |
ss | Seconds 00-59 | {0:ss} | 46 |
tt | AM or PM | {0:tt} | PM |
yy | Year, 2 digits | {0:yy} | 02 |
yyyy | Year | {0:yyyy} | 2002 |
zz | Timezone offset, 2 digits | {0:zz} | -05 |
zzz | Full timezone offset | {0:zzz} | -05:00 |
: | Separator | {0:hh:mm:ss} | 10:43:20 |
/ | Separator | {0:dd/MM/yyyy} | 10/12/2002 |
Enumerations
Specifier | Type |
g | Default (Flag names if available, otherwise decimal) |
f | Flags always |
d | Integer always |
x | Eight digit hex. |
Some Useful Examples
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);
This will output "$1,240.00" if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string "Zero" if the number is zero.
String.Format("{0:(###) ###-####}", 18005551212);
This will output "(800) 555-1212".
变量.ToString()
字符型转换 转为字符串
12345.ToString("n"); //生成 12,345.00
12345.ToString("C"); //生成 ¥12,345.00
12345.ToString("e"); //生成 1.234500e+004
12345.ToString("f4"); //生成 12345.0000
12345.ToString("x"); //生成 3039 (16进制)
12345.ToString("p"); //生成 1,234,500.00%
String.Split 方法有6个重载函数:
2) public string[] Split(char[] separator, int count)
3) public string[] Split(char[] separator, StringSplitOptions options)
4) public string[] Split(string[] separator, StringSplitOptions options)
5) public string[] Split(char[] separator, int count, StringSplitOptions options)
6) public string[] Split(string[] separator, int count, StringSplitOptions options)
下边我们通过一些实例来说明下怎么使用(以下string words = "1,2.3,,4";):
1. public string[] Split(params char[] separator)
string[] split = words.Split(new Char[] { ',', '.' });//返回:{"1","2","3","","4"}
2. public string[] Split(char[] separator, int count)
string[] split = words.Split(new Char[] { ',', '.' }, 6);//返回:{"1","2","3","","4"}
3. public string[] Split(char[] separator, StringSplitOptions options)
string[] split = words.Split(new Char[] { ',', '.' }, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
4. public string[] Split(string[] separator, StringSplitOptions options)
string[] split = words.Split(new string[] { ",", "." }, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
5. public string[] Split(char[] separator, int count, StringSplitOptions options)
string[] split = words.Split(new Char[] { ',', '.' }, 6, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
6. public string[] Split(string[] separator, int count, StringSplitOptions options)
string[] split = words.Split(new string[] { ",", "." }, 6, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
需要注意的是没有重载函数public string[] Split(string[] separator),所以我们不能像VB.NET那样使用words.Split(","),而只能使用words.Split(',')!很多人都很奇怪为什么把双引号改为单引号就可以了?看了上边的重载函数该知道答案了吧^_^