2

I have a string of text and I need to check the string for words that begin with the letter A, then print said words to console.

So far, I have converted the string into its individual parts but am not sure how to go about using substring or StartsWith and an if statement to then feed it to Console.WriteLine.

This is my code so far.

static void Main(string[] args)
{
  string text = "Anna and Jenny went to America to eat some apples";
  string[] words = text.Split(' ');
  
  foreach (string word in words)
  {
  
  }
gunr2171
  • 16,104
  • 25
  • 61
  • 88
Kageus
  • 31
  • 3
  • 3
    `if (word.StartsWith('A')) Console.WriteLine(word);`. Or the case-insensitive equivalent: `if (word.StartsWith("A", StringComparison.OrdinalIgnoreCase)) Console.WriteLine(word);`. – Johnathan Barclay Feb 21 '23 at 14:24

4 Answers4

1

You've got two options here, we can write:

if (word.StartsWith("A")) { Console.WriteLine(word); }

Running this, would give you "Anna", "America".

or

if (word[0] == 'A') { Console.WriteLine(word); }

Running this, would give you "Anna", "America".

These two options are case sensitive, if this is your objective then great, if you're wanting a solution which accepts both cases, we can do:

if (word.StartsWith("A", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine(word); }

or

if (word[0].ToString().Equals("A", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine(word); }

Running the above would get you: "Anna", "and", "America" and "apples".

What the latter example does (word[0]) is it gets the first character from your word to compare, my examples provide you with three ways you can compare the first letter of the string, note that using word[0] will always return a single character (data type char) so you won't be able to test for more than one character at a time!

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Adrian
  • 8,271
  • 2
  • 26
  • 43
  • 1
    Your last snippet does not work as you are comparing a char with a string – Klaus Gütter Feb 21 '23 at 14:32
  • You're right, updated! – Adrian Feb 21 '23 at 14:33
  • You could also write `word[0] == 'A' || word[0] == 'a'` – Klaus Gütter Feb 21 '23 at 14:35
  • 1
    @gunr2171 Not quite, the second example is demonstrating case insensitivity - you'll see that's done in the first example already. – Adrian Feb 21 '23 at 14:36
  • 1
    @KlausGütter Yes, you could, many ways to write it, just keeping it simple really given OP is a beginner :-) – Adrian Feb 21 '23 at 14:37
  • Thanks a lot for this! While I was mucking around offline I figured out that I could get the console to print "Anna" "and" "America" "Apples" by putting in two if statements to include both the upper and lower case A. foreach (string word in words) { if (word.StartsWith("A")) { Console.WriteLine(word); } if (word.StartsWith("a")) { Console.WriteLine(word); } } – Kageus Feb 21 '23 at 15:05
  • But now that I look at your code and compare it to mine, I think what I've done is too 'easy' and will probably cause errors of some kind. I'm just too green to see any. Also sorry for my poor formatting. I couldn't figure out a way to format code into a comment! – Kageus Feb 21 '23 at 15:08
  • @Kageus No problem, your solution that you came up is good but ideally you'd put that into one if statement like so `if (word.StartsWith("A") || word.StartsWith("a"))`. The double pipe `||` means "or", so either of these conditions must be true for your `Console.WriteLine` to print in the console. You won't get bugs as such since you're checking for specific casing but if you were to introduce case insensitivity, you'd need to remove the other if statement as you'd get double results. Good luck! – Adrian Feb 21 '23 at 15:33
0

You can try matching word with a help of regular expressions; if we define word as

Non-empty sequence of letters and apostrophes

you can put it as follow

using System.Linq;
using System.Text.RegularExpressions;

...

string text = "Anna and Jenny went to America to eat some apples";

var words = Regex
  .Matches(text, @"A[\p{L}']*")
  .Cast<Match>()
  .Select(match => match.Value);

foreach (string word in words) {
  //TODO: Relevant Code Here  
}

Pattern A[\p{L}']* explained:

A         - letter A followed by
[\p{L}']* - Zero or more letters (\p{L}) or apostrophes

If you want to ignore case (apples will be included), just do it:

var words = Regex
  .Matches(text, @"A[\p{L}']*", RegexOptions.IgnoreCase)
  ...

Fiddle

Note, that matching is more accurate in case when punctuation is used e.g.

string text = "Anna, would you like to go to America, Africa or Antarctica?";

where we expect to get {Anna, America, Africa, Antarctica}, if you Split you'll get {Africa} only.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
-1

you just have to use the StartsWith and ToUpper Or ToLower for case sensitive :

foreach (string word in words)
  {
      if (word.ToUpper().StartsWith("A")) {
        Console.WriteLine(word);
      }
  }
Pentiminax
  • 19
  • 2
  • If you're going to transform the entire casing of `word` (which, IMO, is wasteful), at least use [`ToUpperInvariant()`](https://stackoverflow.com/questions/3550213/in-c-sharp-what-is-the-difference-between-toupper-and-toupperinvariant) – gunr2171 Feb 21 '23 at 14:39
-1

Same thing as Adrian's excellent answer, but in LINQ form:

String text = "Anna and Jenny went to America to eat some apples";
var words = text.Split(" ".ToCharArray()).Where(x => x.StartsWith("a", StringComparison.OrdinalIgnoreCase));
foreach (var word in words)
{
    Console.WriteLine(word);
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • Why `.Split(" ".ToCharArray())` instead of simple `.Split(' ')`? – Dmitry Bychenko Feb 21 '23 at 16:08
  • Because that's the way I always write it; so if I need to add other things besides a space to split on, they can be listed in there and the code doesn't need other changes. – Idle_Mind Feb 21 '23 at 18:55