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 (' ');
- /// Example 1: GetWordFromText("one two three", 2) should return "two"
- /// Example 2: GetWordFromText("one;two three", 2) should return "three"
- /// Example 3: GetWordFromText("one", 1) should return "one"
- /// When input parameter wordNumberToFind is less than 1, method should throw
- /// ArgumentOutOfRangeException. When input text does not have enough words
- /// (GetWordFromText("one", 2)), method should throw ArgumentException.
- /// When input is null method should throw `ArgumentNullException`.
- /// Method should ignore all spaces in the beginning and in the end of input text.
- /// </returns>
- public string GetWordFromText(string input, int wordNumberToFind)
- {
- // TODO: Implement logic HERE
- 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];
- }
- namespace TaskLib.Tests
- {
- using System;
- using FluentAssertions;
- using NUnit.Framework;
- [TestFixture]
- public class StringTests
- {
- [Test]
- public void When_WordToFindIsNotInTheInput_Then_ArgumentExceptionIsThrown()
- {
- // Arrange
- var tested = new StringHelpers();
- // Act
- Assert.Throws<ArgumentException>(() => { var word = tested.GetWordFromText("two words", 3); });
- }
- [Test]
- public void When_InputTextContainsFewWords_Then_ProperOneIsReturned()
- {
- // Arrange
- var tested = new StringHelpers();
- // Act
- var word = tested.GetWordFromText("one;two three", 2);
- // Assert
- word.Should().Be("three");
- }
- [Test]
- public void When_InputTextIsSymmetrical_Then_ItIsReturned()
- {
- // Arrange
- var tested = new StringHelpers();
- // Act
- var reversed = tested.Reverse("evil live");
- // Assert
- reversed.Should().Be("evil live");
- }
- [Test]
- public void When_InputTextIsPassed_Then_ItIsReversed()
- {
- // Arrange
- var tested = new StringHelpers();
- // Act
- var reversed = tested.Reverse("abcd efgh");
- // Assert
- reversed.Should().Be("hgfe dcba");
- }
- }
- }

games bxsPosted Oct 4, 2019, 2:31 AM
It's hard for me really, I need to do it and learn more
Sourav Kumar DasPosted Sep 30, 2019, 11:30 PM
Good Article.