ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

VBA String Reversal

VBA (Visual Basic for Applications)

Goal -- WPM

Ready
Exercise Algorithm Area
1Function ReverseString(inputString As String) As String
2' Reverses a given string.
3' Handles empty strings and single-character strings gracefully.
4
5Dim reversedString As String
6Dim i As Integer
7Dim len As Integer
8
9len = Len(inputString)
10reversedString = ""
11
12' Handle edge case: empty string
13If len = 0 Then
14ReverseString = ""
15Exit Function
16End If
17
18' Handle edge case: single character string
19If len = 1 Then
20ReverseString = inputString
21Exit Function
22End If
23
24' Iterate from the last character to the first
25For i = len To 1 Step -1
26' Append the current character to the reversed string
27reversedString = reversedString & Mid(inputString, i, 1)
28Next i
29
30ReverseString = reversedString
31End Function
Algorithm description viewbox

VBA String Reversal

Algorithm description:

This VBA function, `ReverseString`, takes a string as input and returns a new string with the characters in reverse order. It's a common string manipulation task used in various applications, such as preparing data for display, simple text processing, or as a building block for more complex string algorithms. The implementation uses a straightforward loop to achieve the reversal.

Algorithm explanation:

The `ReverseString` function iterates through the input string from the last character to the first, appending each character to a new string. This process effectively builds the reversed string. The time complexity is O(n), where n is the length of the string, because each character is processed once. The space complexity is also O(n) because a new string of potentially the same length is created to store the reversed result. Edge cases like an empty string or a string with a single character are handled explicitly to ensure correct output without unnecessary processing. The loop boundary `For i = len To 1 Step -1` ensures that all characters are included in the reversal.

Pseudocode:

Function ReverseString(inputString):
  Initialize reversedString = empty string
  Get length of inputString
  If length is 0, return empty string
  If length is 1, return inputString
  Loop from i = length down to 1:
    Append the character at position i of inputString to reversedString
  Return reversedString