I'm trying to find a way to count the number of chars in a certain word starting with a certain char from a given string in c# using only system.
So for example for the following string "the weather outside is beautiful"
. If I want to count the number of chars for the word "outside" using as a rule just the first letter (in this case will be "o"), can I count somehow the number of chars preceding the o? (in this case will be 6).
I was thinking that it should be something like:
If word starts with "o" than count the following chars and stop counting when we find space, return number.
I tried finding something similar but unfortunately I wasn't successful.
As an addition, there will be only one word starting with the letter o. (or another letter which will be used as a finding rule)
I hope the question is clear enough and thank you in advance!
CodePudding user response:
Perhaps use Regex
:
var text = "the weather outside is beautiful";
var regex = new Regex(@"(o.*?)\b");
var length = regex.Match(text).Captures[0].Length;
Console.WriteLine(length);
That gives 7
.
CodePudding user response:
The general approach would be to
- Split() string by spaces: you get a list of words
- iterate list and check first letter of each word
- if word starts with 'o': get the lenght of word
you can do this either using String.Split()
- leveraging System.Linq
, or even by using simple loops.
Using loops:
public class Program
{
public static void Main()
{
var text = "the weather outside is beautiful";
var word = "";
foreach( var l in text)
{
if (word == "" && l == 'o')
{
word = l;
}
else if (word != "" && l == ' ')
{
System.Console.WriteLine(string.Format("{0} : {1}",
word, word.Length));
word = "";
}
else if (word != "")
{
word = l;
}
}
}
}
This (and the others) output:
outside : 7
Using String.Split()
:
public class Program
{
public static void Main()
{
var text = "the weather outside is beautiful";
var words = text.Split(' ');
foreach( var w in words)
{
if (w.StartsWith("o"))
System.Console.WriteLine(string.Format("{0} : {1}",
w, w.Length));
}
}
}
Using Linq:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var text = "the weather outside is beautiful";
var splitted = text
.Split(' ')
.Where(w => w.StartsWith("o", StringComparison.OrdinalIgnoreCase));
foreach(var w in splitted)
System.Console.WriteLine(string.Format("{0} : {1}", w, w.Length));
}
}