How to return text from a text string

Best practices, code snippets for common functionality, examples, and guidelines.
jmchughsmart
Posts: 28
Joined: Wed Aug 12, 2015 6:44 pm

How to return text from a text string

Post by jmchughsmart » Thu Sep 17, 2015 1:37 pm

Hi

I just want to return 'Robertsbr1234' from 'varCellItemName'

varCellItemName = "Robertsbr1234, jim";
int varLocation = varCellItemName.IndexOf(",");

I can find the index of "," which is 13 (zero based).
how to just get 'Robertsbr1234'

Thanks

jmchughsmart
Posts: 28
Joined: Wed Aug 12, 2015 6:44 pm

Re: How to return text from a text string

Post by jmchughsmart » Thu Sep 17, 2015 2:10 pm

kinda figured it out

string input= varCellItemName;
int stop = input.IndexOf(",");
string output = input.Substring(0, stop);

This displays "Robertsbr1234"

krstcs
Ranorex Guru
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: How to return text from a text string

Post by krstcs » Thu Sep 17, 2015 2:54 pm

You can also use the "Split()" function of the string class.

string result = "Robertsbr1234, jim".Split(',')[0];

Split() returns an array of strings, and you want the 1st one (0-based index in .NET).

If you want a specific string out of the array, you would need to loop over the array.
Shortcuts usually aren't...