0

i'm looking for a way to delete specific chars from a string.

The string contains of letters and digits. I want to cut the last or last 2 digits. They are always digits and always the last or last 2 digits. I know what i want to cut.

string s = lblTemperature104;
int thermometer 4;

In the above case the result should be "lblTemperature10"

Should be looking something like this. Sorry if it's hard to understand but i can't think of another way.

public void stringCutter (string s, int toCut){
     s.cutFromBehind(toCut);

If you have trouble to understand my question feel free to ask. Thank you!

Eppok
  • 55
  • 1
  • 7
  • Shouldn't the result be "lblTemperature1"? You cut off two characters from the end, so, in my opinion, it should be just "lblTemperature1" – deralbert May 04 '20 at 10:43
  • Hey Eppok, what is with your issue? Please let me know if your problem wasn't solved, otherwise you could pick the best answer for your question. – deralbert May 11 '20 at 11:57

2 Answers2

0

You can use regular expressions to achieve this scenario.

Regular Expression: (.*)\w{2}

You can also make use of Remove() which is used for shortening strings and eliminates a range of characters.

string str = "lblTemperature104";
str= str.Remove(str.Length - 2);
Abhishek Duppati
  • 610
  • 6
  • 18
0

If I understand your question correctly, you need to delete two last characters from your string.

First, we correct your code, it should be:

string s = "lblTemperature104";
int thermometer = 4;

The second thing is: There is no difference between letters and numbers when you work with the type string.

The third thing is the answer to your question: You actually don't need one extra function stringCutter, if you will use the String.Remove method like so:

s = s.Remove(s.Length - 1, lng);

lng here is the number of characters that you want to delete. If you will always delete only 2 characters, you can just write:

s = s.Remove(s.Length - 1, 2);

That is just another possible solution. But as Graham Ormond mentioned, you can do the same with the String.Substring. According to this question, the String.Substring is faster than String.Remove.

deralbert
  • 856
  • 2
  • 15
  • 33