新建一个项目quanbanjiao,在此项目下新建一个类Class1
1 using System; 2 using System.Web; 3 using System.Text; 4 5 namespace quanbanjiao 6 { 7 public class Class1 8 { 9 /**/ 10 /// <summary> 11 /// 判断字符是否英文半角字符或标点 12 /// </summary> 13 /// <remarks> 14 /// 32 空格 15 /// 33-47 标点 16 /// 48-57 0~9 17 /// 58-64 标点 18 /// 65-90 A~Z 19 /// 91-96 标点 20 /// 97-122 a~z 21 /// 123-126 标点 22 /// </remarks> 23 public static bool IsBjChar(char c) 24 { 25 int i = (int)c; 26 return i >= 32 && i <= 126; 27 } 28 29 /**/ 30 /// <summary> 31 /// 判断字符是否全角字符或标点 32 /// </summary> 33 /// <remarks> 34 /// <para>全角字符 - 65248 = 半角字符</para> 35 /// <para>全角空格例外</para> 36 /// </remarks> 37 public static bool IsQjChar(char c) 38 { 39 if (c == '\u3000') return true; 40 41 int i = (int)c - 65248; 42 if (i < 32) return false; 43 return IsBjChar((char)i); 44 } 45 46 /* http://www.cnblogs.com/roucheng/ */ 47 /// <summary> 48 /// 将字符串中的全角字符转换为半角 49 /// </summary> 50 public static string ToBj(string type,string s) 51 { 52 if (s == null || s.Trim() == string.Empty) return s; 53 54 StringBuilder sb = new StringBuilder(s.Length); 55 for (int i = 0; i < s.Length; i++) 56 { 57 if (s[i] == '\u3000') 58 sb.Append('\u0020'); 59 else if (IsQjChar(s[i])) 60 sb.Append((char)((int)s[i] - 65248)); 61 else 62 sb.Append(s[i]); 63 } 64 65 //如果是int类型的,则只能输入int类型,否则自动设为0 66 67 if (type.ToLower() == "int") 68 { 69 try 70 { 71 Convert.ToInt32(sb.ToString()); 72 } 73 catch 74 { 75 return "0"; 76 } 77 78 } 79 80 81 82 //如果是float或double类型的,则只能输入这两种类型,否则自动设为0 83 if (type.ToLower() == "float" || type.ToLower() == "double") 84 { 85 try 86 { 87 Convert.ToDouble(sb.ToString()); 88 } 89 catch 90 { 91 return "0"; 92 } 93 } 94 return sb.ToString(); 95 } 96 } 97 }
测试的例子:
using System; using System.Web; using quanbanjiao;//项目名称为quanbanjiao namespace quanbanjiao { public partial class WebForm1 : System.Web.UI.Page { // keleyi.com protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { TextBox1.Text = Class1.ToBj("string", TextBox1.Text.Trim()); } } }