Home > Net >  How to output specific character in the array
How to output specific character in the array

Time:12-28

I have exercise in Course project which I've been struggling to solve B), I can`t find information in Internet how to output specific character in the list of array. The assignment is:

The elements of the array are names of towns beginning with an uppercase letter.

  • A) entering the elements of the array (no more than 50)
  • B) output all towns in whose names the letter "e" or "E" occurs 2,3 or 4 times, and the letter "r" does not occur even once.

I only wrote A) and it is:

string\[\] city;
city = new string \[50\] {i listed 50 cities}

The language I use is C#.

Thank you in advance!

CodePudding user response:

First part of the code string[] cities = { "varna", "burgas", "var", "sofia", "eseema", "peteeee" };

And here u go

    foreach (var city in cities)
        {
            if (city.ToLower().Contains("r"))
            {
                Console.WriteLine(city);
            }

            var eCount = city.ToLower().Count(x => x.ToString().Equals("e"));
            if (eCount >= 2 && eCount <= 4)
            {
                Console.WriteLine(city);
            }

        }

you can do something like that. Hope its help

CodePudding user response:

You can initialize a string-array with:

var cities = new string[] { "New York", "Chicago", ... , "Stockholm", "Helsinki" };

However, the assignment seem to ask the student to create a program that will accept input from the user of the program. For this you can use Console.ReadLine:

var cities = new string[50];
int i=0;
do {
    cities[i  ] = Console.ReadLine();
} while(cities[i-1].Length>1 && i<50);

Keep entering cities until i reaches 50 or user sends an empty string.

To output cities only containing 'E' or 'e' and not cities containing 'r':

foreach(var city in cities)
{
    if((city.Contains("e") || city.Contains("E")) && !city.Contains("r"))
        Console.WriteLine(city);
}

You need to count the number E or e occurs in the city-string, but I leave that as a task for you to figure out. I hope this is helpful on your path to the solution.

CodePudding user response:

We can print a string in C using puts(), printf(), for loop, and recursion method. We have to pass a string character array name in the puts() function as an argument to print the string in the console. We can use the %s format specifier in the printf() function to print the character array in the console.

  •  Tags:  
  • c#
  • Related