How to reverse a string without affecting special characters in C#

1 Answer

0 votes
using System;

public class Program
{
	public static string reverseStringWithoutTheSpecialCharacters(string str) {
		int right = str.Length - 1;
		char[] arr = str.ToCharArray();
		int left = 0;

		while (left < right) {
			if (!char.IsLetter(arr[left])) {
				left++;
			}
			else if (!char.IsLetter(arr[right])) {
				right--;
			}
			else {
				char tmp = arr[left];
				arr[left] = arr[right];
				arr[right] = tmp;

				left++;
				right--;
			}
		}
		return new string(arr);
	}
	public static void Main(string[] args)
	{
		string str = "ab*#cde!@$,fg{}";

		str = reverseStringWithoutTheSpecialCharacters(str);

		Console.Write(str);
	}
}




/*
run:
  
gf*#edc!@$,ba{}
  
*/

 



answered Aug 23, 2022 by avibootz
...