Why string.TrimEnd not removing only last character in string - c#

I have string as below
2,44,AAA,BBB,1,0,,,
So now i want to remove only last comma in above string. So i want output as
2,44,AAA,BBB,1,0,,
I decided to use TrimeEnd as below
str.ToString.TrimEnd(',')
But it removed all the commas after 0. So i get output as below
2,44,AAA,BBB,1,0
Why it removes all the 3 commas after 0? I just need to remove last character in string

Why it removes all the 3 commas after 0?
Because that's what it's documented to do:
Return value:
The string that remains after all occurrences of the characters in the trimChars parameter are removed from the end of the current string.
If you only want the final character removed, you could use:
if (str.EndsWith(","))
{
str = str.Substring(0, str.Length - 1);
}
Or equivalently:
if (str.EndsWith(","))
{
str = str.Remove(str.Length - 1);
}

That is expected. String.TrimEnd Removes all trailing occurrences of a set of characters specified in an array from the current String object
The TrimEnd(char[] trimChars) method removes from the current string all trailing characters that are in the trimChars parameter. The trim operation stops when the first character that is not in trimChars is encountered at the end of the string
Use this instead:
str = str.EndsWith(",") ? str.Substring(0, str.Length - 1) : str;

You can use this:
string s = "2,44,AAA,BBB,1,0,,,";
s = s.Remove(s.Length-1, 1);

Remember Please, the TrimEnd() is not an inplace function. You should reassign its result to str:
str = str.TrimEnd(',')

Related

C# - Split a string separated by ':'

Im trying to split this string:
PublishDate: "2011-03-18T11:08:07.983"
I tried Split method but it's not successful.
str.Split(new[] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries)
As a result I get PublishDate 2011-03-18T11 08 07.983
But correct result is PublishDate 2011-03-18T11:08:07.983
What i need to do?
Split(String, Int32, StringSplitOptions)
Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.
str.Split(':', 2, StringSplitOptions.RemoveEmptyEntries)
https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-6.0#system-string-split(system-string-system-int32-system-stringsplitoptions)
I would solve like this:
locate the index of the first :. The property name will be all the characters before this, which you can extract with Substring and Trim to remove whitespace before the colon, if present.
locate the index of the first " and last ". Characters between the first and last quotes are the property value.
string input = "PublishDate: \"2011-03-18T11:08:07.983\"";
int iColon = input.IndexOf(':');
int iOpenQuote = input.IndexOf('"', iColon);
int iCloseQuote = input.LastIndexOf('"');
string propertyName = input.Substring(0, iColon).Trim();
string propertyValue = input.Substring(iOpenQuote + 1, iCloseQuote - iOpenQuote - 1);
This does not handle escaped characters within the property value (for example, to embed a literal quote or newline using a typical escape sequence like \" or \n). But it's likely good enough to extract a date/time string, and permits all characters because of the use of LastIndexOf. However, this is not robust against malformed input, so you will want to add checks for missing colon, or missing quote, or what happens when the close quote is missing (same same index for start and end quote).
So if I got you right, you want as a result: PublishDate 2011-03-18T11:08:07.983.
Then I would recommend you to use the string.Replace method.
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
string yourData = "PublishDate: \"2011-03-18T11:08:07.983\"";
// First replace the colon and the space after the PublishDate with and space
// then replace the quotes from the timestamp -> "2011-03-18T11:08:07.983"
yourData = yourData.Replace(": ", " ").Replace("\"", "");
// Output the result -> PublishDate 2011-03-18T11:08:07.983
Console.WriteLine(yourData);
}
}

Delete string from a double in C#

I am sending data from arduino to c# and have a problem. The value I get from the serialread comes with an "\r" at the end of it, example: "19.42\r". I found a solution to delete the characters after my number by using Regex. But it also makes my double an integer. "19.42\r" becomes "1942". How can I delete my string but still keep the value as a double?
line = Regex.Replace(line, #"[^\d]", string.Empty);
You want to trim the whitespace from the end of the string.
Use
line = line.TrimEnd();
See the C# demo
If you need to actually extract a double number from a string with regex, use
var my_number = string.Empty;
var match = Regex.Match(line, #"[0-9]+\.[0-9]+");
if (match.Success)
{
my_number = match.Value;
}
If the number can have no fractional part, use #"[0-9]*\.?[0-9]+" regex.
string data = "19.42\r";
return data.Substring(0, data.Length - 1);
or even better
data.TrimEnd('\r')
if \r is fixed characters you want to remove
string str = "awdawdaw\r";
str = str.replace("\r","");
if \r is not fixed characters you want to remove
string str = "awdawdaw\\";
str = str.Substring((str.Length - 2), 2); \\will be removed

String "de-concatenation"

I have two strings like this
string s = "abcdef";
string t = "def";
I would like to remove t from s. Can I do this like this?
s = s - t?
EDIT
I will have two strings s and t, t will be an ending substring of s. I want to remove t from s.
No, but you can do this:
var newStr = "abcdef".Replace("def", "");
Per your comments, if you want to only remove the trailing pattern you can use a Regex:
var newStr = Regex.Replace("defdefdef", "(def)$", "");
The '$' will anchor to the end of the string, so it will only remove the final 'def'
Turning this into an extension method:
public static String ReplaceEnd(this string input, string subStr, string replace = "")
{
//Per Alexei Levenkov's comments, the string should
// be escaped in order to avoid accidental injection
// of special characters into the Regex pattern
var escaped = Regex.Escape(subStr);
var pattern = String.Format("({0})$", escaped);
return Regex.Replace(input, pattern, replace);
}
Using this method with your code above would become:
string s = "abcdef";
string t = "def";
s = s.ReplaceEnd(t); // Ta Da!
Like this:
if (s.EndsWith(t))
{
s = s.Substring(0, s.LastIndexOf(t));
}
s = s.Substring(0, s.Length - t.Length)
Substring takes two arguments: start and length. You want to take things from the start of abcdef, that's index 0, and you want to take all the characters minus the characters from t, which is the difference of length of the two strings.
This assumes the OP's contract of "t will be an ending substring of s". If in fact this precondition is not guaranteed, it needs if (s.EndsWith(t)) around it.

Remove the last three characters from a string

I want to remove last three characters from a string:
string myString = "abcdxxx";
Note that the string is dynamic data.
read last 3 characters from string [Initially asked question]
You can use string.Substring and give it the starting index and it will get the substring starting from given index till end.
myString.Substring(myString.Length-3)
Retrieves a substring from this instance. The substring starts at a
specified character position. MSDN
Edit, for updated post
Remove last 3 characters from string [Updated question]
To remove the last three characters from the string you can use string.Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.
myString = myString.Substring(0, myString.Length-3);
String.Substring Method (Int32, Int32)
Retrieves a substring from this instance. The substring starts at a
specified character position and has a specified length.
You can also using String.Remove(Int32) method to remove the last three characters by passing start index as length - 3, it will remove from this point to end of string.
myString = myString.Remove(myString.Length-3)
String.Remove Method (Int32)
Returns a new string in which all the characters in the current
instance, beginning at a specified position and continuing through the
last position, have been deleted
myString = myString.Remove(myString.Length - 3, 3);
I read through all these, but wanted something a bit more elegant. Just to remove a certain number of characters from the end of a string:
string.Concat("hello".Reverse().Skip(3).Reverse());
output:
"he"
The new C# 8.0 range operator can be a great shortcut to achieve this.
Example #1 (to answer the question):
string myString = "abcdxxx";
var shortenedString = myString[0..^3]
System.Console.WriteLine(shortenedString);
// Results: abcd
Example #2 (to show you how awesome range operators are):
string s = "FooBar99";
// If the last 2 characters of the string are 99 then change to 98
s = s[^2..] == "99" ? s[0..^2] + "98" : s;
System.Console.WriteLine(s);
// Results: FooBar98
myString.Remove(myString.Length-3);
string test = "abcdxxx";
test = test.Remove(test.Length - 3);
//output : abcd
You can use String.Remove to delete from a specified position to the end of the string.
myString = myString.Remove(myString.Length - 3);
Probably not exactly what you're looking for since you say it's "dynamic data" but given your example string, this also works:
? "abcdxxx".TrimEnd('x');
"abc"
If you're working in C# 8 or later, you can use "ranges":
string myString = "abcdxxx";
string trimmed = myString[..^3]; // "abcd"
More examples:
string test = "0123456789", s;
char c;
c = test[^3]; // '7'
s = test[0..^3]; // "0123456"
s = test[..^3]; // "0123456"
s = test[2..^3]; // "23456"
s = test[2..7]; // "23456"
//c = test[^12]; // IndexOutOfRangeException
//s = test[8..^3]; // ArgumentOutOfRangeException
s = test[7..^3]; // string.Empty
str= str.Remove(str.Length - 3);
myString.Substring(myString.Length - 3, 3)
Here are examples on substring.>>
http://www.dotnetperls.com/substring
Refer those.
string myString = "abcdxxx";
if (myString.Length<3)
return;
string newString=myString.Remove(myString.Length - 3, 3);
Easy. text = text.remove(text.length - 3). I subtracted 3 because the Remove function removes all items from that index to the end of the string which is text.length. So if I subtract 3 then I get the string with 3 characters removed from it.
You can generalize this to removing a characters from the end of the string, like this:
text = text.remove(text.length - a)
So what I did was the same logic. The remove function removes all items from its inside to the end of the string which is the length of the text. So if I subtract a from the length of the string that will give me the string with a characters removed.
So it doesn't just work for 3, it works for all positive integers, except if the length of the string is less than or equal to a, in that case it will return a negative number or 0.
Remove the last characters from a string
TXTB_DateofReiumbursement.Text = (gvFinance.SelectedRow.FindControl("lblDate_of_Reimbursement") as Label).Text.Remove(10)
.Text.Remove(10)// used to remove text starting from index 10 to end
items.Remove(items.Length - 3)
string.Remove() removes all items from that index to the end. items.length - 3 gets the index 3 chars from the end
You can call the Remove method and pass the last 3 characters
str.Substring(str.Length-3)
Complete code can be
str.Remove(str.Substring(str.Length-3));

Regex removing double/triple comma in string

I need to parse a string so the result should output like that:
"abc,def,ghi,klm,nop"
But the string I am receiving could looks more like that:
",,,abc,,def,ghi,,,,,,,,,klm,,,nop"
The point is, I don't know in advance how many commas separates the words.
Is there a regex I could use in C# that could help me resolve this problem?
You can use the ,{2,} expression to match any occurrences of 2 or more commas, and then replace them with a single comma.
You'll probably need a Trim call in there too, to remove any leading or trailing commas left over from the Regex.Replace call. (It's possible that there's some way to do this with just a regex replace, but nothing springs immediately to mind.)
string goodString = Regex.Replace(badString, ",{2,}", ",").Trim(',');
Search for ,,+ and replace all with ,.
So in C# that could look like
resultString = Regex.Replace(subjectString, ",,+", ",");
,,+ means "match all occurrences of two commas or more", so single commas won't be touched. This can also be written as ,{2,}.
a simple solution without regular expressions :
string items = inputString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(",", items);
Actually, you can do it without any Trim calls.
text = Regex.Replace(text, "^,+|,+$|(?<=,),+", "");
should do the trick.
The idea behind the regex is to only match that, which we want to remove. The first part matches any string of consecutive commas at the start of the input string, the second matches any consecutive string of commas at the end, while the last matches any consecutive string of commas that follows a comma.
Here is my effort:
//Below is the test string
string test = "YK 002 10 23 30 5 TDP_XYZ "
private static string return_with_comma(string line)
{
line = line.TrimEnd();
line = line.Replace(" ", ",");
line = Regex.Replace(line, ",,+", ",");
string[] array;
array = line.Split(',');
for (int x = 0; x < array.Length; x++)
{
line += array[x].Trim();
}
line += "\r\n";
return line;
}
string result = return_with_comma(test);
//Output is
//YK,002,10,23,30,5,TDP_XYZ

Categories

Resources