
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse a Given String Word by Word Using C#
Create a method reverse Words that takes char array as an input and for each and every character until the empty space is not reached reverse the word. At the last step reverse the entire string from length 0 to n-1 length. In the first step the string “This is my book” will be turned into “koob ym si siht”. At the end of the second step the string words will be reversed to “book my is This”
Time complexity − O(N)
Example
using System; namespace ConsoleApplication{ public class Arrays{ static void reverse(char[] str, int start, int end){ char temp; while (start <= end){ temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } public char[] reverseWords(char[] s){ int start = 0; for (int end = 0; end < s.Length; end++){ if (s[end] == ' '){ reverse(s, start, end); start = end + 1; } } reverse(s, 0, s.Length - 1); return s; } } class Program{ static void Main(string[] args){ Arrays a = new Arrays(); string s = " This is my book "; var res = a.reverseWords(s.ToCharArray()); Console.WriteLine(new String(res)); Console.ReadLine(); } } }
Output
book my is This
Advertisements