/// <summary>
/// 汉字转拼音缩写
/// </summary>
/// <param name="str">要转换的汉字字符串</param>
/// <returns>拼音缩写</returns>
public string GetPYString(string str)
{
string tempStr = "";
foreach(char c in str)
{
if((int)c >= 33 && (int)c <=126)
{//字母和符号原样保留
tempStr += c.ToString();
}
else
{//累加拼音声母
tempStr += GetPYChar(c.ToString());
}
}
return tempStr;
}
/// <summary>
/// 取单个字符的拼音声母
/// </summary>
/// <param name="c">要转换的单个汉字</param>
/// <returns>拼音声母</returns>
public string GetPYChar(string c)
{
byte[] array = new byte[2];
array = System.Text.Encoding.Default.GetBytes(c);
int i = (short)(array[0] - '/0') * 256 + ((short)(array[1] - '/0'));
if ( i < 0xB0A1) return "*";
if ( i < 0xB0C5) return "a";
if ( i < 0xB2C1) return "b";
if ( i < 0xB4EE) return "c";
if ( i < 0xB6EA) return "d";
if ( i < 0xB7A2) return "e";
if ( i < 0xB8C1) return "f";
if ( i < 0xB9FE) return "g";
if ( i < 0xBBF7) return "h";
if ( i < 0xBFA6) return "g";
if ( i < 0xC0AC) return "k";
if ( i < 0xC2E8) return "l";
if ( i < 0xC4C3) return "m";
if ( i < 0xC5B6) return "n";
if ( i < 0xC5BE) return "o";
if ( i < 0xC6DA) return "p";
if ( i < 0xC8BB) return "q";
if ( i < 0xC8F6) return "r";
if ( i < 0xCBFA) return "s";
if ( i < 0xCDDA) return "t";
if ( i < 0xCEF4) return "w";
if ( i < 0xD1B9) return "x";
if ( i < 0xD4D1) return "y";
if ( i < 0xD7FA) return "z";
return "*";
}
2.窗体移动
1.将下面的代码粘贴到Form1类中
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
2.在Form1中改写鼠标消息
protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case WM_NCHITTEST:
base.WndProc(ref m);
if ((int)m.Result == HTCLIENT)
m.Result = (IntPtr)HTCAPTION;
return;
break;
}
base.WndProc(ref m);
}
3.读写二进制文件
StreamReader sr = new StreamReader(this.openFileDialog1.FileName,System.Text.Encoding.Default);
ArrayList arrbuffer = new ArrayList();
//读入所有内容
while(sr.Peek()!=-1)
{
arrbuffer.Add(sr.ReadLine());
}
lines = (string[])arrbuffer.ToArray(typeof(string));
this.textBox1.Lines = lines;
this.textBox1.SelectionLength = 0;
sr.Close();
4.滚动条
int top=0;//全局变量
private void vScrollBar1_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e)
{
if(top<this.vScrollBar1.Value)
{
this.groupBox1.Top=this.groupBox1.Top-(this.vScrollBar1.Value-top);
this.groupBox2.Top=this.groupBox2.Top-(this.vScrollBar1.Value-top);
this.pictureBox1.Top=this.pictureBox1.Top-(this.vScrollBar1.Value-top);
this.button1.Top=this.button1.Top-(this.vScrollBar1.Value-top);
}
else if(top>this.vScrollBar1.Value)
{
this.groupBox1.Top=this.groupBox1.Top-(this.vScrollBar1.Value-top);
this.groupBox2.Top=this.groupBox2.Top-(this.vScrollBar1.Value-top);
this.pictureBox1.Top=this.pictureBox1.Top-(this.vScrollBar1.Value-top);
this.button1.Top=this.button1.Top-(this.vScrollBar1.Value-top);
}
top=this.vScrollBar1.Value;
}
5.只允许运行一个程序
[STAThread]
static void Main()
{
bool createdNew;
System.Threading.Mutex m= new Mutex(true,"列车查询售票系统",out createdNew);
if(createdNew)
{
Application.Run(new Form1());
m.ReleaseMutex();
}
else
{
MessageBox.Show("你已经运行了该系统");
}
}
7.签证数字
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[-]?/d+[.]?/d*$");
if(reg1.IsMatch(str))
{
//数字
}
else
{
//非数字
}
8.生成缩略图
if(fileupload.PostedFile!=null)
{
//addto为要添加的属性,aboutfile为文件说明
string nam = fileupload.PostedFile.FileName ;
//取得文件名(抱括路径)里最后一个"."的索引
int i= nam.LastIndexOf(".");
//取得文件扩展名
string newext =nam.Substring(i);
//这里我自动根据日期和文件大小不同为文件命名,确保文件名不重复
DateTime now = DateTime.Now;
string newname=now.DayOfYear.ToString()+fileupload.PostedFile.ContentLength.ToString();
//保存文件到你所要的目录,这里是IIS根目录下的upload目录.你可以改变.
//注意: 我这里用Server.MapPath()取当前文件的相对目录.在ASP.NET里"/"必须用"//"代替,把"upload//"改成"[url=file://upload//]//upload//[/url]"就成了取当前文件的绝对目录了
fileupload.PostedFile.SaveAs(Server.MapPath("upload//"+newname+newext));
//得到这个文件的相关属性:文件名,文件类型,文件大小
//fname.Text=myFile.PostedFile.FileName;
//fenc.Text=myFile.PostedFile.ContentType ;
//fsize.Text=myFile.PostedFile.ContentLength.ToString();
//下面是生成缩略图
System.Drawing.Image image,aNewImage;
int width,height,newwidth,newheight;
image=System.Drawing.Image.FromFile(Server.MapPath("upload/"+newname.ToString()+newext.ToString()));
System.Drawing.Image.GetThumbnailImageAbort callb =new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
width=image.Width;
height=image.Height;
if(firstpageshow.SelectedValue.ToString()=="1"&&fenlei.SelectedValue.ToString()=="5")
{
newwidth=203;newheight=86;
newheight=height*newwidth/width;
}
else if(isweekman.SelectedValue.ToString()=="1")
{
newwidth=171;newheight=111;
newheight=height*newwidth/width;
}
else if(firstpageshow.SelectedValue.ToString()=="1"&&fenlei.SelectedValue.ToString()=="3")
{
newwidth=171;newheight=111;
newheight=height*newwidth/width;
}
else
{
newwidth=62;newheight=80;
newheight=height*newwidth/width;
}
aNewImage=image.GetThumbnailImage(newwidth,newheight,callb,new System.IntPtr());
aNewImage.Save(Server.MapPath("upload//"+"small_"+newname+newext));
image.Dispose();
//生成缩略图 生成并保存完毕,保存名是在原图名前加了一个small_。
pic="upload/"+newname.ToString()+newext.ToString();
smallpic="upload/small_"+newname.ToString()+newext.ToString();
}
.常用函数
1、DateTime 数字型
System.DateTime currentTime=new System.DateTime();
1.1 取当前年月日时分秒
currentTime=System.DateTime.Now;
1.2 取当前年
int 年=currentTime.Year;
1.3 取当前月
int 月=currentTime.Month;
1.4 取当前日
int 日=currentTime.Day;
1.5 取当前时
int 时=currentTime.Hour;
1.6 取当前分
int 分=currentTime.Minute;
1.7 取当前秒
int 秒=currentTime.Second;
1.8 取当前毫秒
int 毫秒=currentTime.Millisecond;
(变量可用中文)
1.9 取中文日期显示——年月日时分
string strY=currentTime.ToString("f"); //不显示秒
1.10 取中文日期显示_年月
string strYM=currentTime.ToString("y");
1.11 取中文日期显示_月日
string strMD=currentTime.ToString("m");
1.12 取当前年月日,格式为:2003-9-23
string strYMD=currentTime.ToString("d");
1.13 取当前时分,格式为:14:24
string strT=currentTime.ToString("t");
2、字符型转换 转为32位数字型
Int32.Parse(变量) Int32.Parse("常量")
3、 变量.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%
4、变量.Length 数字型
取字串长度:
如: string str="中国";
int Len = str.Length ; //Len是自定义变量, str是求测的字串的变量名
5、字码转换 转为比特码
System.Text.Encoding.Default.GetBytes(变量)
如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str);
然后可得到比特长度:
len = bytStr.Length;
6、System.Text.StringBuilder("")
字符串相加,(+号是不是也一样?)
如:
System.Text.StringBuilder sb = new System.Text.StringBuilder("");
sb.Append("中华");
sb.Append("人民");
sb.Append("共和国");
7、变量.Substring(参数1,参数2);
截取字串的一部分,参数1为左起始位数,参数2为截取几位。
如:string s1 = str.Substring(0,2);
8、取远程用户IP地址
String user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
9、穿过代理服务器取远程用户真实IP地址:
if(Request.ServerVariables["HTTP_VIA"]!=null){
string user_IP=Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}else{
string user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
}
10、存取Session值
Session["变量"];
如,赋值:
Session["username"]="小布什";
取值:
Object objName=Session["username"];
String strName=objName.ToString();
清空:
Session.RemoveAll();
11、用超链接传送变量
String str=Request.QueryString["变量"];
如在任一页中建超链接:<a href=Edit.aspx?fbid=23>点击</a>
在Edit.aspx页中取值:String str=Request.QueryString["fdid"];
12、创建XML文档新节点
DOC对象.CreateElement("新建节点名");
13、将新建的子节点加到XML文档父节点下
父节点.AppendChild(子节点);
14、 删除节点
父节点.RemoveChild(节点);
15、向页面输出:Response
Response.Write("字串");
Response.Write(变量);
跳转到URL指定的页面:
Response.Redirect("URL地址");
16、查指定位置是否空字符
char.IsWhiteSpce(字串变量,位数)——逻辑型;
如:
string str="中国 人民";
Response.Write(char.IsWhiteSpace(str,2)); //结果为:True, 第一个字符是0位,2是第三个字符。
17、查字符是否是标点符号
char.IsPunctuation(''字符'') --逻辑型
如:
Response.Write(char.IsPunctuation(''A'')); //返回:False
18、把字符转为数字,查代码点,注意是单引号。
(int)''字符''
如:
Response.Write((int)''中''); //结果为中字的代码:20013
19、把数字转为字符,查代码代表的字符:(char)代码
如:
Response.Write((char)22269); //返回“国”字。
20、 清除字串前后空格: Trim()
21、字串替换
字串变量.Replace("子字串","替换为")
如:
string str="中国";
str=str.Replace("国","央"); //将国字换为央字
Response.Write(str); //输出结果为“中央”
再如:(这个非常实用)
string str="这是<script>脚本";
str=str.Replace("<","<font><</font>"); //将左尖括号替换为<font> 与 < 与 </font> (或换为<,但估计经XML存诸后,再提出仍会还原)
Response.Write(str); //显示为:“这是<script>脚本”
如果不替换,<script>将不显示,如果是一段脚本,将运行;而替换后,脚本将不运行。
这段代码的价值在于:你可以让一个文本中的所有HTML标签失效,全部显示出来,保护你的具有交互性的站点。
具体实现:将你的表单提交按钮脚本加上下面代码:
string strSubmit=label1.Text; //label1是你让用户提交数据的控件ID。
strSubmit=strSubmit.Replace("<","<font><</font>");
然后保存或输出strSubmit。
用此方法还可以简单实现UBB代码。
22、取i与j中的最大值:Math.Max(i,j)
如 int x=Math.Max(5,10); // x将取值 10
加一点吧 23、字串对比......
23、字串对比一般都用: if(str1==str2){ } , 但还有别的方法:
(1)、 string str1; str2
//语法: str1.EndsWith(str2); __检测字串str1是否以字串str2结尾,返回布尔值.如:
if(str1.EndsWith(str2)){ Response.Write("字串str1是以"+str2+"结束的"); }
(2)、 //语法:str1.Equals(str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.
(3)、 //语法 Equals(str1,str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.
24、查找字串中指定字符或字串首次(最后一次)出现的位置,返回索引值:IndexOf() 、LastIndexOf(), 如:
str1.IndexOf("字"); //查找“字”在str1中的索引值(位置)
str1.IndexOf("字串");//查找“字串”的第一个字符在str1中的索引值(位置)
str1.IndexOf("字串",3,2);//从str1第4个字符起,查找2个字符,查找“字串”的第一个字符在str1中的索引值(位置)
25、在字串中指定索引位插入指定字符:Insert() ,如:
str1.Insert(1,"字");在str1的第二个字符处插入“字”,如果str1="中国",插入后为“中字国”;
26、在字串左(或右)加空格或指定char字符,使字串达到指定长度:PadLeft()、PadRight() ,如:
<%
string str1="中国人";
str1=str1.PadLeft(10,''1''); //无第二参数为加空格
Response.Write(str1); //结果为“1111111中国人” , 字串长为10
%>
27、从指定位置开始删除指定数的字符:Remove()
28.反转整个一维Array中元素的顺序。
har[] charArray = "abcde".ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(new string(charArray));
29.判断一个字符串中的第n个字符是否是大写
string str="abcEEDddd";
Response.Write(Char.IsUpper(str,3));
http://www.chinacs.net/archives/1/2006/3515.html
12345.ToString("C"); //生成 ¥12,345.00
取字符的ASCII码 string s="012aBC"; int asc=(int)s[3];
10.读文件
path1 = this.openFileDialog1.FileName;
FileStream fs = new FileStream(path1,FileMode.Open,FileAccess.Read);
Byte[] b= new byte[fs.Length];//用文件流的长度实例化数组的长度
Encoding data = Encoding.GetEncoding("GB2312");
fs.Read(b,0,b.Length);
string str = data.GetString(b);
fs.Flush();
fs.Close();
11.写文件
string path = this.saveFileDialog1.FileName;
FileStream fs = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write);
byte[] b=data.GetBytes(f22.textBox1.Text);
fs.Write(b,0,b.Length);
fs.Flush();
fs.Close();
12.Datagirdview实现数据分页.
public partial class Form1 : Form
{
SqlDataAdapter sqlDa;
DataSet ds = new DataSet();
int sum;//储存数据集表中的行数
int count = 0;//页数
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection("server=.;uid=sa;database=pubs");
sqlDa = new SqlDataAdapter("select * from jobs", sqlCon);
sqlDa.Fill(ds, "jobs");
//取数据集中的总行数
sum = ds.Tables["jobs"].Rows.Count;
ds.Tables["jobs"].Clear();
//显示3行数据
sqlDa.Fill(ds, 0, 3, "jobs");
dataGridView1.DataSource = ds.Tables["jobs"];
}
//下一页
private void nextBtn_Click(object sender, EventArgs e)
{
if (count >= 0 && count <= sum-3)
{
count += 3;
}
if (ds.Tables["jobs"] != null)
{
ds.Tables["jobs"].Clear();
}
sqlDa.Fill(ds, count, 3, "jobs");
dataGridView1.DataSource = ds.Tables["jobs"];
}
//上一页
private void previousBtn_Click(object sender, EventArgs e)
{
if (count >= 3 && count <= sum)
{
count-= 3;
}
if (ds.Tables["jobs"] != null)
{
ds.Tables["jobs"].Clear();
}
sqlDa.Fill(ds, count, 3, "jobs");
dataGridView1.DataSource = ds.Tables["jobs"];
}
}
13.String类
1. 在string.Format中使用d格式。
int i = 123;
double j = 123.45;
// {0,7:d}表示第0个参数,宽度7位,不够7位左边用空格填充,d表示十进制整数
string s1 = string.Format("the value is {0,7:d}",i);
Console.WriteLine(s1); //结果 the value is 123
// {0,7:f3}表示第0个参数,总宽度7位,其中小数部分占3位,不够7位左边填空格
// f表示浮点数
string s2 = string.Format("the value is {0,7:f3}",j);
Console.WriteLine(s2); //结果 the value is 123.450
2. 在ToString中使用f格式。
double i = 12345.6789;
// f2表示浮点数小数部分为2位,多余部分四舍五入,不够2位时右边补零
string str = i.ToString("f2");
Console.WriteLine(str); //结果 12345.68
string str1 = i.ToString("f6");
Console.WriteLine(str1); //结果 12345.678900
3. 在ToString中使用n格式。
double i = 12345.6789;
// n表示整数部分从小数点向左每3位用逗号分隔开,小数部分2位,多余部分四舍五入
string str = i.ToString("n");
Console.WriteLine(str); //结果 12,345.68
// n4表示整数部分从小数点向左每3位用逗号分隔开,小数部分4位,多余部分四舍五入
string str1 = i.ToString("n4");
Console.WriteLine(str1); //结果 12,345.6789
4. 在ToString中使用p格式。
double i = 0.126;
// p表示百分数形式
string s = string.Format("the value is {0:p}",i);
Console.WriteLine(s); //结果 the value is 12.60%
string str = i.ToString("p");
Console.WriteLine(str); //结果 12.60%
5. 日期与时间的格式化表示。
DateTime dt = new DateTime(2006,5,25);
// yy表示年占两位,M表示月占1位,超出1位按实际位数
// d表示日占1位,超出1位按实际位数
string str = dt.ToString("yy.M.d");
Console.WriteLine(str); //结果 06.5.25
//yyyy表示年占4位,M表示月占1位,超出1位按实际位数,其他按原字符输出
string str1 = dt.ToString("yyyy年M月");
Console.WriteLine(str1); //结果 2006年5月
6. 指定位数和对齐方式。
int i = 123;
double j = 123.45;
// {0,-7}表示第0个参数左对齐,占7位,不够7位右边补空格。
// {1,7}表示第1个参数右对齐,占7位,不够7位左边补空格。
string s = string.Format("i:{0,-7}, j:{1,7}", i, j);
Console.WriteLine(s); //结果i:123 ,j: 123.45
7. 使用占位符表示。
int i = 00012;
string str = string.Format("{0:###,###.00}",i);
Console.WriteLine(str); //结果12.00
i = 0;
str = string.Format("{0:###}", i);
Console.WriteLine(str); //结果什么都不输出
8.常用字符串操作方法
生成字符串
string str1 = "this is a string.";
string str2 = str1;
string str3 = new string('a',4);
Console.WriteLine(str3); //结果为aaaa
查找指定字符串在字符串中出现的位置
IndexOf(string str)
LastIndexOf(string str)
填充字符到字符串中使总长度等于指定长度
PadLeft(总长度,字符)
PadRight(总长度,字符)
例如:
string str = "a";
string str1 = str.PadLeft(5,'e');
Console.WriteLine(str1); //结果为eeeea
string str2 = str.PadRight(5,'e');
Console.WriteLine(str2); //结果为aeeee