C# 替换由数字和字母组成的字符串中第一个出现的0
我正在尝试从字符串的整数部分删除前0。 如果C# 替换由数字和字母组成的字符串中第一个出现的0,c#,string,C#,String,我正在尝试从字符串的整数部分删除前0。 如果“CATI-09100”具有0在integer部分中的第一个,则将其移除,字符串将为“CATI-9100”。否则就没有变化。我尝试使用子字符串。但我需要更好、更有效的方法。而且,“CATI-”将出现在每个字符串中。任何暗示都行 我在想以下几句话: strICTOID = Convert.ToString(drData.GetValue(0).Equals(System.DBNull.Value) ? string.Empty : drData.GetV
“CATI-09100”
具有0
在integer
部分中的第一个,则将其移除,字符串将为“CATI-9100”
。否则就没有变化。我尝试使用子字符串
。但我需要更好、更有效的方法。而且,“CATI-”
将出现在每个字符串中。任何暗示都行
我在想以下几句话:
strICTOID = Convert.ToString(drData.GetValue(0).Equals(System.DBNull.Value) ? string.Empty : drData.GetValue(0).ToString().Trim());
if (strICTOID.Length > 0)
{
indexICTO = strICTOID.IndexOf("-");
}
使用简单的字符串替换
string text = "CATI-09100";
string newText = text.Replace("-0", "-"); // CATI-9100
使用简单的字符串替换
string text = "CATI-09100";
string newText = text.Replace("-0", "-"); // CATI-9100
参考
参考
你可以用这样的东西-
string check = indexICTO.Split('-')[1]; // will split by "-"
if(check[0].Equals("0")) // will check if the charcter after "-" is 0 or not
indexICTO = indexICTO.Replace("-0", "-");
你可以用这样的东西-
string check = indexICTO.Split('-')[1]; // will split by "-"
if(check[0].Equals("0")) // will check if the charcter after "-" is 0 or not
indexICTO = indexICTO.Replace("-0", "-");
这是一个新手的方式,但肯定有效
string myString , firstPart,secondPart ;
int firstNumValue;
myString = "CATI-09994";
string[] parts = myString.Split('-');
firstPart = parts[0];
secondPart = parts[1];
firstNumValue = int.Parse(secondPart.Substring(0, 1));
if(firstNumValue == 0){
secondPart = secondPart.Remove(0,1);
}
Console.WriteLine(firstPart+"-"+secondPart);
这是一个新手的方式,但肯定有效
string myString , firstPart,secondPart ;
int firstNumValue;
myString = "CATI-09994";
string[] parts = myString.Split('-');
firstPart = parts[0];
secondPart = parts[1];
firstNumValue = int.Parse(secondPart.Substring(0, 1));
if(firstNumValue == 0){
secondPart = secondPart.Remove(0,1);
}
Console.WriteLine(firstPart+"-"+secondPart);
如果要删除整数开头的所有零,可以执行以下操作:
your_string = Regex.Replace(your_string, @"-0+(\d+)", "$1");
//CATI-009100 --> CATI-9100
//CATI-09100 --> CATI-9100
//CATI-9100 --> CATI-9100
如果要删除整数开头的所有零,可以执行以下操作:
your_string = Regex.Replace(your_string, @"-0+(\d+)", "$1");
//CATI-009100 --> CATI-9100
//CATI-09100 --> CATI-9100
//CATI-9100 --> CATI-9100
我们不需要先检查0是否存在吗?这样不包含0的字符串就不会中断。尽管您的解决方案简单易行。如果它没有找到零,它也不会改变字符串。我们不需要先检查0是否存在吗?这样不包含0的字符串就不会中断。尽管您的解决方案简单易行。与之类似,如果未找到零,则不会更改字符串。是否确实要从字符串的整数部分删除前0?也就是说,如果字符串是“CATI-9102”,您真的希望它返回“CATI-912”吗?也许你只是想去掉前导零。如果有两个前导零-“CATI-0020”-是否要“CATI-020”或“CATI-20”?是否确实要从字符串的整数部分删除前0?也就是说,如果字符串是“CATI-9102”,您真的希望它返回“CATI-912”吗?也许你只是想去掉前导零。如果有两个前导零-“CATI-0020”-您想要“CATI-020”还是“CATI-20”?