Input: Hello AlgoLesson Output: HelloAlgoLesson Input: Good Morning Output: GoodMorning
Approach 1: Using string.Replace Method.
// C# code implementation to remove whitespace from string using System; public class HelloWorld { public static string RemoveSpacesUsingReplace(string input) { return input.Replace(" ", ""); } public static void Main(string[] args) { string str = "Welcome to AlgoLesson"; string result = RemoveSpacesUsingReplace(str); Console.WriteLine ("With Whitespace: " + str); Console.WriteLine ("Without Whitespace: " + result); } }
With Whitespace: Welcome to AlgoLesson Without Whitespace: WelcometoAlgoLesson
Approach 2: Using string.Join Method.
// C# code implementation to remove whitespace from string using Join method using System; public class AlgoLesson { public static string RemoveSpacesUsingSplitAndJoin(string input) { string[] words = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); return string.Join("", words); } public static void Main(string[] args) { string str = "Welcome to AlgoLesson"; string result = RemoveSpacesUsingSplitAndJoin(str); Console.WriteLine ("With Whitespace: " + str); Console.WriteLine ("Without Whitespace: " + result); } }
With Whitespace: Welcome to AlgoLesson Without Whitespace: WelcometoAlgoLesson
Approach 3: Using string Builder.
// C# code implementation to remove whitespace from string using string builder using System; public class HelloWorld { public static string RemoveSpacesUsingStringBuilder(string input) { StringBuilder sb = new StringBuilder(); foreach (char c in input) { if (c != ' ') { sb.Append(c); } } return sb.ToString(); } public static void Main(string[] args) { string str = "Welcome to AlgoLesson"; string result = RemoveSpacesUsingSplitAndJoin(str); Console.WriteLine ("With Whitespace: " + str); Console.WriteLine ("Without Whitespace: " + result); } }
With Whitespace: Welcome to AlgoLesson Without Whitespace: WelcometoAlgoLesson
