Reputation: 3
I have a string and want to check if there is a letter(only one) that is surrounded by spaces. I tried using Regex but something is not right.
Console.Write("Write a string: ");
string s = Console.ReadLine();
string[] results = Regex.Matches(s, @" (a-zA-Z) ")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToArray();
I am not sure if I am doing this right I am new to C#
Upvotes: 0
Views: 316
Reputation: 77294
A full blown RegEx seems to be heavy stuff for such a simple operation.
This is a sample how to do it. It does include a lot of assumptions that might not be true for you (the fact that I don't consider start or end of string a valid whitespace, the fact I check for WhiteSpace instead of blank, you will have to check those assumptions I made).
namespace ConsoleApplication4
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class StringExtensions
{
public static IEnumerable<int> IndexOfSingleLetterBetweenWhiteSpace(this string text)
{
return Enumerable.Range(1, text.Length-2)
.Where(index => char.IsLetter(text[index])
&& char.IsWhiteSpace(text[index + 1])
&& char.IsWhiteSpace(text[index - 1]));
}
}
class Program
{
static void Main()
{
var text = "This is a test";
var index = text.IndexOfSingleLetterBetweenWhiteSpace().Single();
Console.WriteLine("There is a single letter '{0}' at index {1}", text[index], index);
Console.ReadLine();
}
}
}
This should print
There is a single letter 'a' at index 8
Upvotes: 3