简体   繁体   中英

c# comparing first char of string to array of chars for a/an usage

I am writing the code to display the proper a/an in a sentence. Currently it works, but it seems rather redundant. I was thinking an array of vowels could be compared to the first letter, but can't find out how to implement that when googling. How could I do that or is there a better method?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CoreObjectsLibrary;
using BaseObjects;

namespace Deliverable5 {
    /// <summary>
    /// Interaction logic for frmItem.xaml
    /// </summary>
    public partial class frmItem : Window {
        public frmItem(Item newItem) {
            InitializeComponent();
            //Create textblock to display found item's name
            TextBlock itemInfo = new TextBlock();
            itemInfo.TextWrapping = TextWrapping.Wrap;
            //Proper a/an caps because name
            if (newItem.Name[0] == 'A' || newItem.Name[0] == 'E' || newItem.Name[0] == 'I' || newItem.Name[0] == 'O' || newItem.Name[0] == 'U') {
                itemInfo.Text = "You found an: " + newItem.Name;
                stkItemDisplay.Children.Add(itemInfo);
            }
            else {
                itemInfo.Text = "You found a: " + newItem.Name;
                stkItemDisplay.Children.Add(itemInfo);
            }
        }
    }
}

You could replace complete logic(if block) with these lines.

itemInfo.Text = string.Format("You found {0}: {1}", "aeiouAEIOU".IndexOf(newItem.Name[0]) >= 0? "an": "a" , newItem.Name);  
stkItemDisplay.Children.Add(itemInfo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM