Remove last specific character in a string c# - c#

I use WinForms c#.I have string value like below,
string Something = "1,5,12,34,";
I need to remove last comma in a string. So How can i delete it ?

Try string.TrimEnd():
Something = Something.TrimEnd(',');

King King's answer is of course correct, and Tim Schmelter's comment is also good suggestion in your case.
But if you really want to remove the last comma in a string, you should find the index of the last comma and remove it like this:
string s = "1,5,12,34,12345";
int index = s.LastIndexOf(',');
Console.WriteLine(s.Remove(index, 1));
Output will be:
1,5,12,3412345
Here is a demonstration.
It is unlikely that you want this way but I want to point it out. And remember, the String.Remove method doesn't remove any characters in the original string, it returns new string.

Try string.Remove();
string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);

The TrimEnd method takes an input character array and not a string.
The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.
static string TrimTrailingChars(string value)
{
int removeLength = 0;
for (int i = value.Length - 1; i >= 0; i--)
{
char let = value[i];
if (let == '?' || let == '!' || let == '.')
{
removeLength++;
}
else
{
break;
}
}
if (removeLength > 0)
{
return value.Substring(0, value.Length - removeLength);
}
return value;
}

Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))
output:
1,5,12,34,123

Try below
Something..TrimEnd(",".ToCharArray());

Or you can convert it into Char Array first by:
string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];
Now you have each character indexed:
SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','
Play around it

When you have spaces at the end. you can use beliow.
ProcessStr = ProcessStr.Replace(" ", "");
Emails = ProcessStr.TrimEnd(';');

Try this,
string Something1= Something.Substring(0, Something.Length - 1 );

Related

C# WPF Separate characters from a string (starting from the back)

I have such a comic string.
www.asdsad.de/dsfdsf/sdfdsf=dsfdsfs?dsfsndfsajdn=sfdjasdhads=test.xlsx
I would like to get only the test.xlsx out.
So I wanted to say that I wanted to separate the string from behind.
That he he once the first = sign found me the string supplies the from the end to the = sign goes.
Whats the best way to do this?
Unfortunately, I would not know how I should do with SubString, since the length can always be different. But I know that in the end is what I need and the unnecessary with the first = Begin from behind
Yes, Substring will do, and there's no need to know the length:
string source = "www.asdsad.de/dsfdsf/sdfdsf=dsfdsfs?dsfsndfsajdn=sfdjasdhads=test.xlsx";
// starting from the last '=' up to the end of the string
string result = source.SubString(source.LastIndexOf("=") + 1);
Another option:
string source = "www.asdsad.de/dsfdsf/sdfdsf=dsfdsfs?dsfsndfsajdn=sfdjasdhads=test.xlsx";
Stack<char> sb = new Stack<char>();
for (var i = source.Length - 1; i > 0; i--)
{
if (source[i] == '=')
{
break;
}
sb.Push(source[i]);
}
var result = string.Concat(sb.ToArray());

How to extract string at a certain character that is repeated within string?

How can I get "MyLibrary.Resources.Images.Properties" and "Condo.gif" from a "MyLibrary.Resources.Images.Properties.Condo.gif" string.
I also need it to be able to handle something like "MyLibrary.Resources.Images.Properties.legend.House.gif" and return "House.gif" and "MyLibrary.Resources.Images.Properties.legend".
IndexOf LastIndexOf wouldn't work because I need the second to last '.' character.
Thanks in advance!
UPDATE
Thanks for the answers so far but I really need it to be able to handle different namespaces. So really what I'm asking is how to I split on the second to last character in a string?
You can use LINQ to do something like this:
string target = "MyLibrary.Resources.Images.Properties.legend.House.gif";
var elements = target.Split('.');
const int NumberOfFileNameElements = 2;
string fileName = string.Join(
".",
elements.Skip(elements.Length - NumberOfFileNameElements));
string path = string.Join(
".",
elements.Take(elements.Length - NumberOfFileNameElements));
This assumes that the file name part only contains a single . character, so to get it you skip the number of remaining elements.
You can either use a Regex or String.Split with '.' as the separator and return the second-to-last + '.' + last pieces.
You can look for IndexOf("MyLibrary.Resources.Images.Properties."), add that to MyLibrary.Resources.Images.Properties.".Length and then .Substring(..) from that position
If you know exactly what you're looking for, and it's trailing, you could use string.endswith. Something like
if("MyLibrary.Resources.Images.Properties.Condo.gif".EndsWith("Condo.gif"))
If that's not the case check out regular expressions. Then you could do something like
if(Regex.IsMatch("Condo.gif"))
Or a more generic way: split the string on '.' then grab the last two items in the array.
string input = "MyLibrary.Resources.Images.Properties.legend.House.gif";
//if string isn't already validated, make sure there are at least two
//periods here or you'll error out later on.
int index = input.LastIndexOf('.', input.LastIndexOf('.') - 1);
string first = input.Substring(0, index);
string second = input.Substring(index + 1);
Try splitting the string into an array, by separating it by each '.' character.
You will then have something like:
{"MyLibrary", "Resources", "Images", "Properties", "legend", "House", "gif"}
You can then take the last two elements.
Just break down and do it in a char loop:
int NthLastIndexOf(string str, char ch, int n)
{
if (n <= 0) throw new ArgumentException();
for (int idx = str.Length - 1; idx >= 0; --idx)
if (str[idx] == ch && --n == 0)
return idx;
return -1;
}
This is less expensive than trying to coax it using string splitting methods and isn't a whole lot of code.
string s = "1.2.3.4.5";
int idx = NthLastIndexOf(s, '.', 3);
string a = s.Substring(0, idx); // "1.2"
string b = s.Substring(idx + 1); // "3.4.5"

get all characters to right of last dash

I have the following:
string test = "9586-202-10072"
How would I get all characters to the right of the final - so 10072. The number of characters is always different to the right of the last dash.
How can this be done?
You can get the position of the last - with str.LastIndexOf('-'). So the next step is obvious:
var result = str.Substring(str.LastIndexOf('-') + 1);
Correction:
As Brian states below, using this on a string with no dashes will result in the original string being returned.
You could use LINQ, and save yourself the explicit parsing:
string test = "9586-202-10072";
string lastFragment = test.Split('-').Last();
Console.WriteLine(lastFragment);
I can see this post was viewed over 46,000 times. I would bet many of the 46,000 viewers are asking this question simply because they just want the file name... and these answers can be a rabbit hole if you cannot make your substring verbatim using the at sign.
If you simply want to get the file name, then there is a simple answer which should be mentioned here. Even if it's not the precise answer to the question.
result = Path.GetFileName(fileName);
see https://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx
string tail = test.Substring(test.LastIndexOf('-') + 1);
YourString.Substring(YourString.LastIndexOf("-"));
With the latest C# 8 and later you can use Range Indexer as follows:-
string test = "9586-202-10072"
var foo = test?[(test.LastIndexOf('-') + 1)..];
// foo is => 10072
string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");
if (indexOfHyphen >= 0)
{
string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
Console.WriteLine(contentAfterLastHyphen );
}
See String.lastIndexOf method
I created a string extension for this, hope it helps.
public static string GetStringAfterChar(this string value, char substring)
{
if (!string.IsNullOrWhiteSpace(value))
{
var index = value.LastIndexOf(substring);
return index > 0 ? value.Substring(index + 1) : value;
}
return string.Empty;
}
test.Substring[(test.LastIndexOf('-') + 1)..]
C# 8 (late 2019) introduces range operator and simplifies it a bit further. The two dots here means from the index (inclusive) till the end of string.
test.Substring(test.LastIndexOf("-"))
and... in case you need the left part of a string:
private string AllTheLeftPart(string theString)
{
string rightPart = theString.Substring(theString.LastIndexOf('-') + 1);
string leftPart theString.Replace("-" + rightPart, String.Empty);
return leftPart ;
}

Help me delete the last three chars of any string please!

Test string:
the%20matrix%20
How can I delete the last three chars? Using this code gives me an out of index exception:
y = y.Substring(y.Length - 4, y.Length - 1);
Seems this isn't your REAL problem; if you want to remove that "%20", you should use:
string test = "the%20matrix%20";
string clean = HttpUtility.UrlDecode(test);
if (clean.Length > 2) // if you still want to strip last chars...
clean = clean.Substring(0, clean.Length - 3);
As dalovega said, you need the first parameter of Substring to be 0 and the second Length - 3. As an alternative:
if(y.Length >= 3)
{
y = y.Remove(y.Length - 3)
}
You want
y.Substring(0, y.Length-4)
If you want to delete the last three characters, you need the first parameter of your Substring method to be zero.
You need to check that the string is at least 3 characters long first.
if (y.Length > 2)
{
}
As others have said the version of Substring you want parameters are startIndex and length.
Though what do you want to do with 1 or 2 character strings?
I found this post from a search I was looking for. I had a delimiter I was building with a string builder, and concat and wanted to remove the last delimiter.
var delim = "{somedelimiter}";
var sb = new StringBuilder();
//concat the values into one string
foreach (var val in values)
{
sb.Append(val);
sb.Append(delim);
}
var finalValue = sb.ToString();
finalValue = finalValue.Remove(finalValue.Length - delim.Length);
string.Remove(string.LastIndexOf(" stringTo "));

Best way to break a string on the last dot on C#

What would be the best way and more idiomatic to break a string into two at the place of the last dot? Basically separating the extension from the rest of a path in a file path or URL. So far what I'm doing is Split(".") and then String.Join(".") of everything but the last part. Sounds like using a bazooka to kill flies.
If you want performance, something like:
string s = "a.b.c.d";
int i = s.LastIndexOf('.');
string lhs = i < 0 ? s : s.Substring(0,i),
rhs = i < 0 ? "" : s.Substring(i+1);
You could use Path.GetFilenameWithoutExtension()
or if that won't work for you:
int idx = filename.LastIndexOf('.');
if (idx >= 0)
filename = filename.Substring(0,idx);
To get the path without the extension, use
System.IO.Path.GetFileNameWithoutExtension(fileName)
and to get the extenstion (including the dot), use
Path.GetExtension(fileName)
EDIT:
Unfortunately GetFileNameWithoutExtension strips off the leading path, so instead you could use:
if (path == null)
{
return null;
}
int length = path.LastIndexOf('.');
if (length == -1)
{
return path;
}
return path.Substring(0, length);
The string method LastIndexOf maybe of some use to you here.
But the Path or FileInfo operators will be better suited for filename based operations.
I think what you're really looking for is Path.GetFileNameWithoutExtension Method (System.IO) but just for the heck of it:
string input = "foo.bar.foobar";
int lastDotPosition = input.LastIndexOf('.');
if (lastDotPosition == -1)
{
Console.WriteLine("No dot found");
}
else if (lastDotPosition == input.Length - 1)
{
Console.WriteLine("Last dot found at the very end");
}
else
{
string firstPart = input.Substring(0, lastDotPosition);
string lastPart = input.Substring(lastDotPosition + 1);
Console.WriteLine(firstPart);
Console.WriteLine(lastPart);
}
Path.GetExtension() should help you.
What about using the LastIndexOf method which returns the last found position of a character. Then you can use Substring to extract what you want.
String.LastIndexOf will return you the position of the dot if it ever exists in the string. You can then String.Substring methods to split the string.
You can use string's method
LastIndexOf and substring to acomplish the task.

Categories