Chaos
Chaos

Reputation: 33

After String.Reverse, a mistake occurs in ToString

When the application runs, the IDE tells me Input string is not in the correct format.

(Convert.ToInt32(_subStr.Reverse().ToString().Substring(4, _subStr.Length - 4))*1.6).ToString() 

I don't know how the Reverse() can be exactly used here.

Upvotes: 2

Views: 4406

Answers (3)

julian bechtold
julian bechtold

Reputation: 2251

the simplest approach would be:

string backwards = "sdrawkcab";
string reverse = "";
for(int i = backwards.Length-1; i >= 0; i--)
     reverse += backwards[i];

The result is: reverse == "backwards".

then you can do:

reverse = (Convert.ToInt32(reverse) * 1.6).toString();

Your Piping approach string.Substring().Split().Last()... will very quickly lead to a memory bottleneck, if you loop through lines of text.

Also important to notice: strings are Immutable, therefor each iteration of the for loop we create a new string instance in the memory because of the += operator, this will give us less optimal memory efficieny compared to other, more efficient algorithms, this is an O(n2) algorithm.

for a more efficient implementation you can check: https://stackoverflow.com/a/1009707/14473033

Upvotes: 0

Guffa
Guffa

Reputation: 700442

As the Reverse method is an extension of IEnumerable<T>, you get an IEnumerable<T> as result, and as that doesn't override the ToString method, you will get the original implementation from the Object class, that simply returns the type name of the object. Turn the IEnumerable<T> into an array, then you can create a string from it.

You should first get the part of the string that is digits, then reverse it. That way it will work, regardless of what characters you have in the rest of the string. Although using the Reverse extension doesn't work properly to reverse any string (as Thomas Levesque pointed out), it will work for a string with only digits:

(
  Int32.Parse(
    new String(_subStr.SubString(0, _subStr.Length - 4).Reverse().ToArray())
  ) * 1.6
).ToString();

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292475

There is no Reverse method in the String class, so the method you're using is actually the Enumerable.Reverse extension method. This compiles because String implements IEnumerable<char>, but the result is not a string, it's another implementation of IEnumerable<char>. When you call ToString() on that, you get this: System.Linq.Enumerable+<ReverseIterator>d__a01[System.Char]`.

If you want to convert this IEnumerable<char> to a string, you can dot it like this:

string reversed = new string(_subStr.Reverse().ToArray());
(Convert.ToInt32(reversed.Substring(4, _subStr.Length - 4))*1.6).ToString()

Note, however, that it is not a correct way of reversing a string, it will fail in some cases due to Unicode surrogate pairs and combining characters. See here and there for explanations.

Upvotes: 9

Related Questions