Answer the question
In order to leave comments, you need to log in
How to pull out the necessary characters from a string knowing the positions?
It seems not a difficult task, but something I did not understand how best to do it. Here is an example of a file name - N54E026.hgt
The format of the name is always the same - 1 letter / 2 numbers / 1 letter / 3 numbers / + extension. (and hence the location of the desired characters too).
The task is to pull all these positions (1 letter / 2 numbers / 1 letter / 3 numbers) into 4 different variables. What is the best way to do this?
Answer the question
In order to leave comments, you need to log in
"Better" is different: the speed of work, the cost of memory, the clarity of the code.
In terms of speed and memory costs, this option is the most optimal:
static void Parse(string name = "N54E026.hgt")
{
char c1 = name[0];
int n1 = (name[1] - '0') * 10 + (name[2] - '0');
char c2 = name[3];
int n2 = (name[4] - '0') * 100 + (name[5] - '0') * 10 + (name[6] - '0');
}
...
var fn = "N54E026.hgt";
var c1 = fn[0];
Console.WriteLine($"первый символ {c1}");
...
var d2 = fn.Substring(1, 2);
Console.WriteLine($"фрагмент из 2х символов, начиная со второй позиции {d2}");
if(int.TryParse(d2, out var n2))
Console.WriteLine($"численное значение d2 {n2}");
...
string one_char = name[0];
string two_numbers = name[1] + name[2];
string another_one_char = name[3];
//и так далее
Use the ToCharArray() method to convert a string to a character array. For example:
string fileName = "N54E026.hgt";
char[] chars = fileName.ToCharArray();
var first = chars[0];
var second = chars[1] + chars[2];
var third = chars[3];
var fourth = chars[4] + chars[5] + chars[6];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question