Creating Reverse Function

Now we have to make function that will reversing our string. Then, we will loop through that string, but to make it simple, we will looping from both ends.

static string Reverse(string str)
{
    // Initialize left and right pointers
    int left = 0;
    int right = str.Length-1;

    // Traverse string from both ends until
    // 'left' and 'right'
    while (left<right)
    {

    }
    return str;
}

After that, we want to check if every character in string is letter or not so we can ignore the special characters. If neither of them is special character, swap them.

while (left<right)
{
    // Ignore special characters
    if (!(char.IsLetter(str[left])))
    {
        left++;
    }
    else if(!(char.IsLetter(str[right])))
    {
        right--;
    }
    else // Both str[left] and str[right] are not special
    {
        str = SwapCharacters(str, left, right);
        left++;
        right--;
    }
}

As you can see, now we need function for swapping char inside string.

static string SwapCharacters(string value, int position1, int position2)
{
    char[] array = value.ToCharArray(); // Get characters
    char temp = array[position1]; // Get temporary copy of character
    array[position1] = array[position2]; // Assign element
    array[position2] = temp; // Assign element
    return new string(array); // Return string
}

results matching ""

    No results matching ""