I have a bunch of lat/long pairs as a string:
-94.5555,95.5555
The API I'm using requires they be switched:
95.555,-94.555
Is there any slick, short way of doing this?
I have a bunch of lat/long pairs as a string:
-94.5555,95.5555
The API I'm using requires they be switched:
95.555,-94.555
Is there any slick, short way of doing this?
Just write a method to do it, e.g. using string.IndexOf
:
// Probably rename to reflect your specific usage
private static string SwitchSplitOnComma(string text)
{
// Optional: validate that text is non-null
int comma = text.IndexOf(',');
// Optional: validate that there's a comma :)
return text.Substring(comma + 1) + "," + text.Substring(0, comma);
}
Unless you need this for various purposes, I'd leave it as a specialist method in the class that needs it. Only promote it to a "general purpose utility method" (possibly parameterizing the delimiter etc) if you find you need the same functionality elsewhere.
Although you can do this in a single statement, I think the code is likely to be far easier to understand if you put it in a separate method - at which point it's fine to use a few easy-to-understand statements instead of one complicated and inefficient one :)
One-liner with Linq:
string.Join(",", original.Split(',').Reverse());
Or, more explicit (might be a performance improvement):
string[] split = original.Split(',');
string reversed = split[1] + "," + split[0];
string myStr = "-94.5555,95.5555";
string[] components = myStr.Split(",")
components.Reverse();
string flippedStr = string.Join(",", components);
String reversedLatLong = String.Join(",", yourString.Split(',').Reverse());
The most efficient would be to modify/extend the API, since it parses the string anyway. Probably not an option, but I throw it out there...
How about this?
string oldString = "-94.5555,95.5555";
string newString = oldString .Substring(oldString .IndexOf(",") + 1) + "," + oldString .Substring(0, oldString .IndexOf(","));
Building on Jon Skeet's, something more generic would be useful:
private static string Switch(this string text, char splitter)
{
if(text != null && text.Length > 2) //Needs at least 3 letters for a valid switch
{
int position = text.IndexOf(splitter);
if(position != -1) return text.Substring(position + 1) + splitter + text.Substring(0, position);
}
return text;
}
"99,-3432".Switch(',');
Just for the heck of it. Here's a faster version, but you probably wouldn't need it :)
For 1.000.000 iterations compared to Jon Skeets clean version measured in seconds on my machine:
00:00:00.2145657 substring
00:00:00.0781270 unsafe
private unsafe static string SwitchSplitOnComma2(string text)
{
int comma = text.IndexOf(',');
string newString = string.Copy(text);
fixed (char* src = text)
{
fixed (char* dst = newString)
{
int destCtr = 0;
for (int i = comma + 1; i < text.Length; i++)
{
dst[destCtr++] = src[i];
}
dst[destCtr++] = ',';
for (int i = 0; i < comma; i++)
{
dst[destCtr++] = src[i];
}
}
}
return newString;
}