user11753067
user11753067

Reputation:

How to swap huge string

I have huge string e.g (This is just the part, the string looks same it has just a bit different values).

string numbers = "48.7465504247904 9.16364437205161 48.7465666577545 9.16367275419435 48.746927738083 9.16430761814855 48.7471066512883 9.16462219521963 48.7471147950429";

So I have to swap the whole number e.g. Output should be:

9.16364437205161 48.7465504247904

Also I need to swap the first and second part.

So I've tried to split the string, and then to replace the old one with the new one.

string numbers = "48.7465504247904 9.16364437205161 48.7465666577545 9.16367275419435 48.746927738083 9.16430761814855 48.7471066512883 9.16462219521963 48.7471147950429";

string output = "";
double first = 0;
double second = 0;

for (int i = 0; i < numbers.Length; i++)
{
    numbers.Split(' ');
    first = numbers[0];
    second = numbers[1];
}

output = numbers.Replace(numbers[1], numbers[0]);
Console.WriteLine(output);

But my variable first always after the loop has the value 52.

Right now my output is: 44.7465504247904 9.16364437205161, it changed the first part, also it calculates somehow -4 .

Upvotes: 0

Views: 100

Answers (2)

clarkitect
clarkitect

Reputation: 1730

You're not assigning anything to the value coming back from .Split and, if I read this right, you're also iterating each character in the numbers array for unclear reasons.

Using .Split is all you need ... well, and System.Linq

using System.Linq;
// ...
string SwapNumbers(string numbers) {
    return numbers.Split(' ').Reverse().Join();
}

The above assumes you want to reverse the whole series of numbers. It absolutely does not swap 1,2 then swap 3,4 etc. If that's what you're looking for, it's a bit more involved and I'll add that in a second for funsies.

string SwapAlternateNumbers(string numbersInput) {
    var wholeSeries = numbersInput.Split(' ').ToList();

    // odd number of inputs
    if (wholeSeries.Count % 2 != 0) {
        throw new InvalidOperationException("I'm not handling this use case for you.");
    }

    var result = new StringBuilder();

    for(var i = 0; i < wholeSeries.Count - 1; i += 2) {
        // append the _second_ number
        result.Append(wholeSeries[i+1]).Append(" ");
        // append the _first_ number
        result.Append(wholeSeries[i]).Append(" ");
    }

    // assuming you want the whole thing as a string
    return result.ToString();
}

Edit: converted back to input and output string. Sorry about the enumerables; that's a difficult habit to break.

Upvotes: 2

gadasadox
gadasadox

Reputation: 109

here

public static void Main()
    {
        string nums  = "48.7465504247904 9.16364437205161 48.7465504247904 9.16364437205161";
        var numbers = nums.Split(' ');
        var swapped = numbers.Reverse();
        Console.WriteLine("Hello World {"+string.Join(" ",swapped.ToArray())+"}");

    }

Upvotes: -1

Related Questions