因为自己项目开发的需要,需要自己写个函数用于获取料件编号前缀,因为料件编号前缀是用料件类型然后加随机数字组成的,但是料件类型可能是1个,2个,3个等字母开头,我也不可能每个类型都判断,这样是否很难编码这个字符处理代码。其实仔细构思想了下 ,就有了如下代码了,自己做下CODE记录吧。
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualBasic;
using System.Text.RegularExpressions;
namespace ConsoleAppTest
{
public class StringHandle
{
/// <summary>
/// 返回前缀为字母的字符串
/// </summary>
/// <param name="sourceString">要检测的字符串</param>
/// <returns></returns>
public static string getPreCharecterString(string sourceString)
{
char[] initialChar ={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','G','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};//52个字母
//string initialString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//char[] initialDigit ={ '0','1','2','3','4','5','6','7','8','9'};
// initialChar=initialString.ToCharArray();
if (string.IsNullOrEmpty(sourceString))
{
return string.Empty;
}
else
{
string tempStr = string.Empty;// 用于暂存
char[] sourceChar = sourceString.ToCharArray();//把原来的字符转正字符数组
int length = sourceString.Length;//获取字符串长度
for (int i = 0; i < length; )
{
//if (Regex.IsMatch(sourceChar[i].ToString(), @"^[+-]?\d*[.]?\d*$"))//匹配是否是数字,是则直接转向OK标签
//{
// goto ok;
//}
if (!Regex.IsMatch(sourceChar[i].ToString(), @"^[A-Za-z]"))//匹配非字母
{
goto ok;
}
char currentChar = sourceChar[i];
foreach(char okChar in initialChar)
{
if (okChar == currentChar)
{
tempStr += okChar;
}
}
i++;
}
ok:
return tempStr;
}
}
}