Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Working with strings, copying the content

He has been trying to deal with the problem for some time. More precisely, it tries to extract some information from a string:

string source = "1\t\r\nFIRST\t36\t4.976.501\t3.162\t3.121\t26\r\n2\t\r\n";

I would like the end result to look like this:

float firstNumber = 36;
float secondNumber = 4.976.501;
float thirdNumber = 3.162;
float fourthNumber = 3.121;
float fiftNumber = 26;

How could I get information from this string? I tried to use the string.substring method

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int From = St.IndexOf("\t") + "\t".Length;
int To = St.LastIndexOf("\t"); // here's the problem
String result = St.Substring(pFrom, pTo - pFrom);
float firstNumber = float.Parse(result);

The problem is with multiple occurrences of the same / t. I don’t know how I could specify multiple occurrences in string.Substring

>Solution :

There is an overload of String.IndexOf that allows to specify the position from which to search for the next occurence. After getting the first occurence, you use its position plus one when searching for the next occurence. This way, you can search for tabs step by step:

var firstTab = St.IndexOf("\t");
var nextTab = St.IndexOf("\t", firstTab + 1);

An alternative to this approach would be to split the string using the tabs as separator:

var parts = St.Split('\t');

You can then analyse the parts and find the occurences without worrying about string positions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading