'Wanting to format a string so it splits into two strings, I cant quite get the format right
My main input is from a string seperated by a commar, but I am having a hard time to see how to split the string so it send the values to the correct array.
Input format = "39.6, 3.068"
for (int i = 0; i < wholeAdresse.Length; i++)
{
//string phrase = wholeAdresse[index];
string[] output = wholeAdresse[i].Split(',');
foreach (var myOutput in output )
{
//System.Console.WriteLine($"<{myOutput }>");
Alist.Add(myOutput [0]); ---->Hoped for output "39.6"
Blist.Add(myOutput [1]); ---->Hoped for output "3.068"
}
}
How do I fix it?
Solution 1:[1]
As the data items are on lines, it seems very likely that they are associated with each other, for example they could be latitude-longitude pairs. In that case, it would make sense to create a class to represent the data from one line so that all the individual parts can be conveniently kept together instead of you trying to remember which array is for what.
Perhaps something like this console app:
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
public class LatLon
{
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
}
static void Main(string[] args)
{
string[] wholeAdresse = new string[] { "39.6, 3.068", "40.12, 2.998" };
List<LatLon> listA = new List<LatLon>();
for (int i = 0; i < wholeAdresse.Length; i++)
{
string[] output = wholeAdresse[i].Split(',');
listA.Add(new LatLon()
{
Latitude = decimal.Parse(output[0].Trim()),
Longitude = decimal.Parse(output[1].Trim())
});
}
foreach (var ll in listA)
{
Console.WriteLine("Lat: " + ll.Latitude + " Lon: " + ll.Longitude);
}
Console.ReadLine();
}
}
}
Outputs:
Lat: 39.6 Lon: 3.068
Lat: 40.12 Lon: 2.998
Notice how it is easy to use ll.Latitude and ll.Longitude: you'll know what they are.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew Morton |
