Skip to content

Commit f1b2731

Browse files
reverse-string: fix span approach code
1 parent 60212a7 commit f1b2731

File tree

1 file changed

+14
-6
lines changed
  • exercises/practice/reverse-string/.approaches/span

1 file changed

+14
-6
lines changed

exercises/practice/reverse-string/.approaches/span/content.md

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
# Span<T>
22

33
```csharp
4-
Span<char> chars = stackalloc[input.Length];
5-
for (var i = 0; i < input.Length; i++)
4+
public static class ReverseString
65
{
7-
chars[input.Length - 1 - i] = input[i];
6+
public static string Reverse(string input)
7+
{
8+
Span<char> chars = stackalloc[input.Length];
9+
10+
for (var i = 0; i < input.Length; i++)
11+
{
12+
chars[input.Length - 1 - i] = input[i];
13+
}
14+
15+
return new string(chars);
16+
}
817
}
9-
return new string(chars);
1018
```
1119

1220
C# 7.2. introduced the [`Span<T>`][span-t] class, which was specifically designed to allow performant iteration/mutation of _array-like_ objects.
@@ -39,10 +47,10 @@ Span<char> chars = stackalloc char[input.Length];
3947

4048
With this version, the memory allocated for the `Span<char>` is all on the stack and no garbage collection is needed for that data.
4149

42-
~~~~exercism/caution
50+
```exercism/caution
4351
The stack has a finite amount of memory.
4452
This means that for large strings, the above code will result in a `StackOverflowException` being thrown.
45-
~~~~
53+
```
4654

4755
So what is the limit for the amount of memory we can allocate?
4856
Well, this depends on how memory has already been allocated on the stack.

0 commit comments

Comments
 (0)