Home > Enterprise >  Working with strings, copying the content
Working with strings, copying the content

Time:07-16

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

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

CodePudding user response:

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.

CodePudding user response:

You can use the method public string[] Split (params char[]? separator);

string[] parts = St.Split('\t');
float firstNumber = Single.Parse(parts[2].Trim());
float secondNumber = Single.Parse(parts[3].Trim());
float thirdNumber = Single.Parse(parts[4].Trim());
float fourthNumber = Single.Parse(parts[5].Trim());
float fiftNumber = Single.Parse(parts[6].Trim());

Trim removes the \r and \n.

The Single.Parse Method converts the string representation of a number to its single-precision floating-point number equivalent. The C# alias for System.Single is float.

Or you can get the numbers in an array like this

float[] numbers = St.Split('\t')
    .Skip(2)
    .Take(5)
    .Select(s => Single.Parse(s.Trim())
    .ToArray();
  • Related