My string is like this:
string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
Here actually I want to extract the last word, ‘API’, and return.
What would be the C# code to do the above extraction?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, the naive implementation to that would be to simply split on each space and take the last element.
Splitting is done using an instance method on the String object, and the last of the elements can either be retrieved using array indexing, or using the Last LINQ operator.
End result:
If you don’t have LINQ, I would do it in two operations:
While this would work for this string, it might not work for a slightly different string, so either you’ll have to figure out how to change the code accordingly, or post all the rules.
Here, the comma would be part of the “word”.
Also, if the first method of obtaining the word is correct, that is, everything after the last space, and your string adheres to the following rules:
Then you can use this code that will allocate fewer objects on the heap for GC to worry about later:
However, if you need to consider commas, semicolons, and whatnot, the first method using splitting is the best; there are fewer things to keep track of.