简体   繁体   中英

How to check if last char of an array string ends with “A”

I have made an array where the user inputs several names, I then want the program to print them out. If the letter ends with "a" I want it to change color. Here's what I mean in code.

        Array.Sort(stodents);

        Console.WriteLine("----------");

        for (int i = 0; i < stodents.Length; i++)
        {
            if (What do I type here?)
            {
                Console.ForegroundColor = ConsoleColor.Magenta;
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Blue;
            }
            Console.WriteLine(stodents[i]);
        }

So yeah I want it to make the string blue when it doesn't end with an A and magenta when it does.

You could use the String.EndsWith method.

if(stodents[i].EndsWith('a'))

The method checks if the string ends with a specified char/string (depending on the overload you use) and returns true if it finds a match.

You could also use the overload with StringComparison enum if you want to make it case-insensitive check

For example,

if(stodents[i].EndsWith("a",StringComparison.OrdinalIgnoreCase))

Here's one example:

   Array.Sort(students);
    Console.WriteLine("----------");

    foreach (string student in students)
    {
        if (student.EndsWith('A')
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Blue;
        }
        Console.WriteLine(student);
    }

NOTE:

  1. In C#, common to use "foreach()" instead of a "for()" loop.

  2. One solution is to use the .Net API StringEndsWith()

  3. One problem is that your code most end with 'A'. You can "generalize" your code to accomodate either upper or lower case by using String.ToLower() .

'Hope that helps.

PS: As Anu6is correctly pointed out (and as the documentation I cited shows), you can also use an optional StringComparison comparisonType argument for a case-insensitive comparison. The drawback is then you must use a string ( "A" ) instead of a character ( 'A' ).

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