0

I am trying to remove first 0 from integer part of the string. IF "CATI-09100" has 0 first in interger part remove it and string would be "CATI-9100". Otherwise no change. I tried using substring. But I need better and efficient way to do it. Also, "CATI-" will be in every string. Any hint will do.

I was thinking on below lines :

strICTOID = Convert.ToString(drData.GetValue(0).Equals(System.DBNull.Value) ? string.Empty : drData.GetValue(0).ToString().Trim());
            if (strICTOID.Length > 0)
            {
                indexICTO = strICTOID.IndexOf("-");


            }
Ubaid Ashraf
  • 1,049
  • 5
  • 15
  • 43
  • Are you sure you want to remove the first 0 from integer part of the string? That is, if your string is "CATI-9102", do you really want it to return "CATI-912"? Maybe you just want to remove the leading zeros. What if there are two leading zeros - "CATI-0020" - do you want "CATI-020" or "CATI-20"? – FarmerBob Oct 14 '17 at 08:40

5 Answers5

2

Use a simple string replace.

string text = "CATI-09100";

string newText = text.Replace("-0", "-"); // CATI-9100
jegtugado
  • 5,081
  • 1
  • 12
  • 35
2

you can use something like this-

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", "-"); 
1

if you want to remove all the zeros at the begining of an integer you can do this:

your_string = Regex.Replace(your_string, @"-0+(\d+)", "$1");
//CATI-009100 -->  CATI-9100
//CATI-09100  -->  CATI-9100
//CATI-9100   -->  CATI-9100
Tomer Wolberg
  • 1,256
  • 10
  • 22
0

Referencing Replace first occurrence of pattern in a string

var regex = new Regex(Regex.Escape("0"));
var newText = regex.Replace("CATI-09100", "", 1);
davidchoo12
  • 1,261
  • 15
  • 26
0

This is a rookie way but sure works.

        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);
GTP
  • 51
  • 5