E
E
Envywewok2019-05-10 16:52:46
C++ / C#
Envywewok, 2019-05-10 16:52:46

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

4 answer(s)
R
Roman, 2019-05-10
@Envywewok

"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');
}

#
#, 2019-05-10
@mindtester

...
  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}");
...

R
Ronald McDonald, 2019-05-10
@Zoominger

string one_char = name[0];
string two_numbers = name[1] + name[2];
string another_one_char = name[3];
//и так далее

V
Vladimir Kovalev, 2019-05-11
@darkhorse77

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 question

Ask a Question

731 491 924 answers to any question