[英]Extracting an integer from a string
我有一個個人ID和一個行業ID,我想相互比較,但是行業編號的前面有零和一個字母字符。 有些數字比其他數字更長。
例如
Personal Number | Industry Number
123 | J000123
1234 | L001234
12345 | M012345
如果只有零,我知道如何解決該問題。 角色使我四處亂跑,我將如何實現?
我假設PersonalNumber是一個Int
,IndustryNumber是具有String
類型
bool Result = int.Parse(string.Concat(PersonalNumber.Skip(1))) == IndustryNumber;
對於更新的問題(即行業編號以任意字母開頭,后跟一個用零填充的數字),可能是
// Remove 1st letter, than remove zeros
String number = IndustryNumber.Substring(1).TrimStart('0');
if (number.Equals(personalNumber)) {
...
}
使用RegEx:
var numb = int.Parse(RegEx.Match(industryNumber, @"\d+^").Value);
//Then compare the two ints
為下面的給定代碼創建一個函數
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);
然后調用getInt(mystring)== int
由多米尼克回答
Regex.Replace("J0123", "([A-z]*)", "");
您可以使用正則表達式刪除行業編號的第一部分:
Regex.Replace("J0123", "J0*", "");
結果為“ 123”
UPDATE ,要考慮所有字母,請使用此正則表達式:
Regex.Replace("J0123", "[A-Z]0*", "");
您需要在行業編號上使用substring()並在之后進行轉換:我假設您使用二維數組。 字符串[,] myarray。
for (int i = 0; i<myarray.GetLengh(0);i++)
{
//get personnal number as integer, this is simple
int personnal = Convert.ToInt32(myarray[i][0]);
//get industry number as integer, this is the difficult part
string strIndustry = myarray[i][1];
strIndustry = strIndustry.SubString(0,1);//remove the first char
int industry = Convert.ToInt32(strindustry);//I assume that you only have numbers after the letter if not you may need to test it with tryParse...
//then you can now compare integers
if(personnal==industry)
{
//your code to execute if true
}
else{//...}
}
假設您有兩個用於PersonalId和IndustryID的數組.Result是另一個將保存結果的數組。
for(int i=0; i< PersonalID.Count i++)
{
if(IndustryID[i].Contains(PersonalID[i]))
{
Result[i]=true;
}
else
Result[i]=False;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.