How to Remove the last char of String in C#? - c#

I have a numeric string, which may be "124322" or "1231.232" or "132123.00".
I want to remove the last char of my string (whatever it is).
So I want if my string is "99234" became "9923".
The length of string is variable. It's not constant so I can not use string.Remove or trim or some like them(I Think).
How do I achieve this?

YourString = YourString.Remove(YourString.Length - 1);

var input = "12342";
var output = input.Substring(0, input.Length - 1);
or
var output = input.Remove(input.Length - 1);

newString = yourString.Substring(0, yourString.length -1);

If this is something you need to do a lot in your application, or you need to chain different calls, you can create an extension method:
public static String TrimEnd(this String str, int count)
{
return str.Substring(0, str.Length - count);
}
and call it:
string oldString = "...Hello!";
string newString = oldString.TrimEnd(1); //returns "...Hello"
or chained:
string newString = oldString.Substring(3).TrimEnd(1); //returns "Hello"

If you are using string datatype, below code works:
string str = str.Remove(str.Length - 1);
But when you have StringBuilder, you have to specify second parameter length as well.
That is,
string newStr = sb.Remove(sb.Length - 1, 1).ToString();
To avoid below error:

Related

how i can get the string after specific character in my case :?

str="Brand : TROLLBEADS";
int length = str.Length;
length = length - 6;
str = str.Substring(6, length);
i want to display "TROLLBEADS"
and want to discard other remaining string
You can split the string using : delimiter if it is fixed
var result = str.Split(':')[1].Trim();
or if your string can have multiple : in that case
var result = str.Substring(str.IndexOf(":") + 1).Trim();
Split is nice, but a bit too much. You can just specify the start position for substring.
string str="Brand : TROLLBEADS";
string val = str.Substring(str.IndexOf(":") + 1);
Console.WriteLine(val);

how to do substring in reverse mode in c#

My string is "csm15+abc-indiaurban#v2". I want only "indiaurban" from my string. what I am doing right now is :
var lastindexofplusminus = input.LastIndexOfAny(new char[]{'+','-'});
var lastindexofattherate = input.LastIndexOf('#');
string sub = input.Substring(lastindexofplusminus,lastindexofattherate);
but getting error "Index and length must refer to a location within the string."
Thanks in Advance.
You should put the length in the second argument (instead of passing another index) of the Substring you want to grab. Given that you know the two indexes, the translation to the length is pretty straight forward:
string sub = input.Substring(lastindexofplusminus + 1, lastindexofattherate - lastindexofplusminus - 1);
Note, +1 is needed to get the char after your lastindexofplusminus.
-1 is needed to get the Substring between them minus the lastindexofattherate itself.
You can simple reverse the string, apply substring based on position and length, than reverse again.
string result = string.Join("", string.Join("", teste.Reverse()).Substring(1, 10).Reverse());
Or create a function:
public static string SubstringReverse(string str, int reverseIndex, int length) {
return string.Join("", str.Reverse().Skip(reverseIndex - 1).Take(length));
}
View function working here!!
You can use LINQ:
string input = "csm15+abc-indiaurban#v2";
string result = String.Join("", input.Reverse()
.SkipWhile(c => c != '#')
.Skip(1)
.TakeWhile(c => c != '+' && c != '-')
.Reverse());
Console.WriteLine(result); // indiaurban
I don't know what is identify your break point but here is sample which is working
you can learn more about this at String.Substring Method (Int32, Int32)
String s = "csm15+abc-indiaurban#v2";
Char charRange = '-';
Char charEnd = '#';
int startIndex = s.IndexOf(charRange);
int endIndex = s.LastIndexOf(charEnd);
int length = endIndex - startIndex - 1;
Label1.Text = s.Substring(startIndex+1, length);
Assuming that your string is always in that format
string str = "csm15+abc-indiaurban#v2";
string subSTr = str.Substring(10).Substring(0,10);

Errors with splitting string

I'm quite new to programming and I'm trying to split the string below to just 36.20C but I keep getting ArgumentOutOfRangeWasUnhandled. why?
private void button1_Click(object sender, EventArgs e)
{
string inStr = "Temperature:36.20C";
int indexOfSpace = inStr.IndexOf(':');
//stores the address of the space
int indexOfC = inStr.IndexOf("C");
//stores the address of char C
string Temp = inStr.Substring(indexOfSpace + 1, indexOfC);
textBox1.Text = Temp;
}
expected output : 36.20C
The second argument of String.Substring is the length but you have provided the end index. You need to subtract them:
string Temp = inStr.Substring(++indexOfSpace, indexOfC - indexOfSpace);
You could also remove the C from the end:
string Temp = inStr.Substring(++indexOfSpace).TrimEnd('C'); // using the overload that takes the rest
As an aside, you should use the overload of IndexOf with the start-index in this case:
int indexOfC = inStr.IndexOf('C', indexOfSpace);
Here is an easier approach:
Temp = inStr.Split(':').Last().TrimEnd('C');
If you check the documentation for Substring, you'll see that the second parameter is the length, not the end position. However, there is an overload for SubString that only needs the start position and it'll return the string from there to the end of the string:
int indexOfSpace = inStr.IndexOf(':');
string Temp = inStr.Substring(indexOfSpace + 1);
var arrayStr = inStr.split(':');
textbox1.text = arrayStr[1];
you can do it like
string Temp = inStr.Substring(indexOfSpace + 1, inStr.Length - indexOfSpace - 1)
Second parameter of Substring is length. You must update as following:
string Temp = inStr.Substring(indexOfSpace + 1, indexOfC - indexOfSpace);
Just use string.Split().
string[] temp = inStr.Split(':');
textbox1.Text = temp[1];
// temp[1] returns "36.20C"
// temp[0] returns "Temperature"
string temperature = "temperature:32.25C";
Console.WriteLine(temp.Substring(temp.Trim().IndexOf(':')+1));
In substring, 2nd argument is length and if u do not specify any argument substring processes till the end of string.

How to get the remaining string after removing a substring

Suppose, I have the following string:
string temp = "some string contains text which contains demo";
string result = RemainingString(temp, 12, 8); // string, startIndex, length
The result string I need should look as follows:
some string text which contains demo
Note, that the word contains is removed from first place only.
Update: I personally want to achieve this using regular expression explicitly.
Try the String.Remove method, it does exactly what you ask.
String.Remove(Int32, Int32) will do the job:
string temp = "some string contains text which contains demo";
string result = temp.Remove(12,8);
Use string.Remove:
public string RemainingString(string orig, int startIndex, int length)
{
return orig.Remove(startIndex, length);
}
Alternatively - concatenate two substrings - up to the index, and after the index+length (.NET 1.0/1.1):
public string RemainingString(string orig, int startIndex, int length)
{
return orig.Substring(0, startIndex) +
orig.Substring(startIndex + length);
}
Here's a solution using regular expressions:
public string RemainingString(string str, int start, int length)
{
return Regex.Replace(str, "^(.{" + start+ "})(?:.{" + length + "})(.*)$", "$1$2");
}
$line_string = 'this is all the sting from which i would want to treat';
$key_string ='from which';
//use strpos
$position2 = strpos($line_string,$key);
if($position2){
$found = substr($line_string,$position2,strlen($key_string));
//echo $found;
}
//the substr now begins at character position $position2
//and ends at position2 + strlen($key_string);
//so
$remainderpos = position2 + strlen($key_string);
$str_remaining = substr($line_string,$remainderpos);
echo $str_remaining;
as simple as it can get. code from the scratch.

How to Remove Last digit of String in .Net?

I want to eliminate B if i scan Serial number bar code: 21524116476CA2006765B
Output: 21524116476CA2006765
string foo = "21524116476CA2006765B";
string bar = foo.Substring(0, Math.Max(foo.Length - 1, 0));
If you can't be certain that the input barcode will always end with a B, do something like this:
char[] barcodeEnd = { 'B' };
string input = "21524116476CA2006765B";
string output = input.TrimEnd(barcodeEnd);
PUt the first line somewhere it'll only get run once, so you aren't constantly creating new char[] arrays. You can add more characters to the array if you're looking for other specific characters.
string s = "21524116476CA2006765B";
string b = s.Substring(0, s.Length - 1);
string value= "21524116476CA2006765B";
string bar = value.Substring(0, 19);
string str = "Your String Whatever it is";
str = str.Substring(0, s.Length - 1);

Categories