简体   繁体   中英

How to remove last character of a number in C#

This is my string "codes 02 - UFL 1500"

String SelCurItem;                      
String GradeGSM;
Int32 CalcLengthSelCurItem;
Int32 CalcLengthGradeGSM;

CalcLengthSelCurItem = SelCurItem.Length - 11; //this part gives me the first 8 characters back
GradeGSM = SelCurItem.Substring(11, CalcLengthSelCurItem); // gives me "UFL 1500" BACK
CalcLengthGradeGSM = GradeGSM.Length - GradeGSM.IndexOf(" ");
Grade = GradeGSM.Substring(0, GradeGSM.IndexOf(" ")); // GIVES ME "UFL" back
GSM = Convert.ToInt32(GradeGSM.Substring(GradeGSM.IndexOf(" "), CalcLengthGradeGSM)); // GIVES ME "1500"

Now i want to add another field named GSM2 and i want the output to give me back "150" it must drop the last character. How do i achieve this?

我没有用C#编写代码,但是您可以除以10。而且由于它是int类型,所以没有小数。

Try this:

UPDATED

String GSM2 = GSM.ToString().Substring(0,GSM.ToString().Length-1);

Assuming that you obtain GSM2 throw GSM, you can take GSM and discard the last caracter

You can use either:

Int32 GSM2 = GSM1/10;

or

Int32 GSM2 = Int32.Parse(GSM1.ToString().Remove(GSM1.ToString().Length -1));

You could also use regex to split the whole string (and get the last number without the last digit):

var regex = new Regex(@"(?<FirstPart>.{8}) - (?<SecondPart>.{3})\s(?<Number>\d*)(?<LastDigit>\d)");
var match = regex.Match("codes 02 - UFL 1500");
Console.WriteLine(match.Groups["FirstPart"].Value);
Console.WriteLine(match.Groups["SecondPart"].Value);
Console.WriteLine(match.Groups["Number"].Value);
Console.WriteLine(match.Groups["LastDigit"].Value);

// Output:
// codes 02
// UFL
// 150
// 0

You could use Substring

using System;

public class Example
{
   public static void Main()
   {
      String s = "aaaaabbbcccccccdd";
      Char charRange = 'b';
      int startIndex = s.IndexOf(charRange);
      int endIndex = s.LastIndexOf(charRange);
      int length = endIndex - startIndex + 1;
      Console.WriteLine("{0}.Substring({1}, {2}) = {3}",
                        s, startIndex, length, 
                        s.Substring(startIndex, length));
   }
}
// The example displays the following output:
//       aaaaabbbcccccccdd.Substring(5, 3) = bbb

https://msdn.microsoft.com/de-de/library/aka44szs(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM