I will demonstrate how to reverse a string in a simple way and how to find a specfic word in the given string using C#. Here is the code sample that shows you how to reverse a string in C# and find the desired word in a given string.
Reverse a string in simple steps using C#.
- public string ReverseString(string input)
- {
- if (string.IsNullOrEmpty(input))
- {
- throw new ArgumentNullException();
- }
-
- var output = input.Reverse();
- return new string(output.ToArray());
- }
Find a word in given string. We assume the separator of word is space (' ');
-
-
-
-
-
-
-
-
-
- public string GetWordFromText(string input, int wordNumberToFind)
- {
-
-
- if (wordNumberToFind < 1)
- {
- throw new ArgumentOutOfRangeException();
- }
-
- if (string.IsNullOrWhiteSpace(input))
- {
- throw new ArgumentNullException();
- }
-
- var words = input.Split(' ');
-
- if (wordNumberToFind > words.Length)
- {
- throw new ArgumentException();
- }
-
- while (string.IsNullOrWhiteSpace(words[wordNumberToFind - 1]))
- {
- wordNumberToFind++;
- }
-
- return words[wordNumberToFind - 1];
- }
Let's have some unit tests to verify the above code.
- namespace TaskLib.Tests
- {
- using System;
-
- using FluentAssertions;
- using NUnit.Framework;
-
- [TestFixture]
- public class StringTests
- {
- [Test]
- public void When_WordToFindIsNotInTheInput_Then_ArgumentExceptionIsThrown()
- {
-
- var tested = new StringHelpers();
-
-
- Assert.Throws<ArgumentException>(() => { var word = tested.GetWordFromText("two words", 3); });
- }
-
- [Test]
- public void When_InputTextContainsFewWords_Then_ProperOneIsReturned()
- {
-
- var tested = new StringHelpers();
-
-
- var word = tested.GetWordFromText("one;two three", 2);
-
-
- word.Should().Be("three");
- }
-
- [Test]
- public void When_InputTextIsSymmetrical_Then_ItIsReturned()
- {
-
- var tested = new StringHelpers();
-
-
- var reversed = tested.Reverse("evil live");
-
-
- reversed.Should().Be("evil live");
- }
-
- [Test]
- public void When_InputTextIsPassed_Then_ItIsReversed()
- {
-
- var tested = new StringHelpers();
-
-
- var reversed = tested.Reverse("abcd efgh");
-
-
- reversed.Should().Be("hgfe dcba");
- }
- }
- }
Thanks. I hope you liked this simple approach of reversing a string and finding a word in the string.