Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last part of a string?

Tags:

c#

regex

Given this string:

http://s.opencalais.com/1/pred/BusinessRelationType 

I want to get the last part of it: "BusinessRelationType"

I have been thinking about reversing the whole string then looking for the first "/", take everything to the left of that and reverse that. However, I'm hoping there is a better/more concise method. Thoughts?

Thanks, Paul

like image 524
Paul Fryer Avatar asked Aug 02 '10 11:08

Paul Fryer


People also ask

How do you find the last element of a string?

If we want to get the last character of the String in Java, we can perform the following operation by calling the "String. chatAt(length-1)" method of the String class. For example, if we have a string as str="CsharpCorner", then we will get the last character of the string by "str. charAt(11)".

How do I get the last part of a string in Python?

The last character of a string has index position -1. So, to get the last character from a string, pass -1 in the square brackets i.e. It returned a copy of the last character in the string. You can use it to check its content or print it etc.

How do I get the last 3 characters of a string?

Getting the last 3 characters To access the last 3 characters of a string, we can use the built-in Substring() method in C#. In the above example, we have passed s. Length-3 as an argument to the Substring() method.

How do you get the last part of a string before a certain character?

Use the lastIndexOf() method to get the substring before the last occurrence of a specific character, e.g. str. substring(0, str. lastIndexOf('_')); . The substring method will return a new string containing the part of the string before the last occurrence of the specified character.


1 Answers

one-liner with Linq:

var lastPart = text.Split('/').Last(); 

or if you might have empty strings in there (plus null option):

var lastPart = text.Split('/').Where(x => !string.IsNullOrWhiteSpace(x)).LastOrDefault(); 
like image 96
naspinski Avatar answered Sep 23 '22 03:09

naspinski