Question Creating a blog

Ellenjernstrom

New member
Joined
Dec 18, 2021
Messages
3
Programming Experience
Beginner
Hey everyone, I hope you're doing great today.

I'm a beginner in C# and I have an assignment where I need to create a blog:
These are the criteria that need to be included in the assignment;
  • The blog should be a list that can save string arrays. Each individual blog post should be a string array. The vectors must contain at least two elements. NOTE: You may not replace the vector list with a class.
  • A working menu with choices for the program's functionality, use SWITCH.
  • Measures to prevent driving time errors.
  • Opportunity to print posts from the blog.
  • Opportunity to save new blog posts, with at least title and message.
  • Opportunity to search for posts in the blog, for example on the title of the post.
    Your search should be based on a comparison between a keyword and the title of each post. Other forms of the search may be included as an alternative, or to show that you can handle more advanced tools, but there must be a basic search that compares the title of each post with a keyword.
  • Well-commented code that explains and justifies the choice of data types, control structures, methods, data structures, and algorithms.
My issue now is my linear search in case 3... I'm only able to find the first post that has been saved but not the other posts that have been saved as well.
I've been in contact with my teacher about my issue and I tried to solve it by using contains but I was not allowed to do so. She told me to only use a regular linear search with equality operators.
I will insert my code for the kind soul that wants to attend to help me. I've spent numerous hours/days on this and I just can't find what's causing the issue.

NOTE: My comments are in Swedish but I hope you can read my code anyway


C#:
using System;
//Jobbar med listor och då behöver vi lägga in följande kod för att komma åt list-klassen.
using System.Collections.Generic;

namespace Bloggen.komplettering
{
    class Program

    {
        static void Main(string[] args)
        {
            //Deklarera min lista så användaren senare skall kunna söka efter sina inlägg i arkivet vid menyval 3.
            List<string[]> archive = new List<string[]>();

            //Sant eller falsk variabel som kommer ge mig mer kontroll i när programmet körs eller inte.
            bool ellensBool = true;

            // Skriver ut en hälsning på skärmen till användaren.
            Console.WriteLine("\n\tHej och välkommen till din egna blogg!\n\t");
            //Avskärmare av avsikt för ren estetik
            Console.WriteLine("_______________________________________" + "\n\t");

            //Loppen börjar.
            while (ellensBool)
            {
                //Tar bort onödig text för varje gång loopen börjar om.
                Console.Clear();
                //Skapar min meny
                Console.WriteLine("\tVänligen gör ett av följande menyval: ");
                Console.WriteLine("\t[1]Skriv ett nytt blogginlägg: ");
                Console.WriteLine("\t[2]Skriv ut dina sparade blogginlägg");
                Console.WriteLine("\t[3]Sök efter dina sparade blogginlägg i arkivet");
                Console.WriteLine("\t[4]Stäng ner bloggen och avsluta programmet!");
                Console.Write("\nVälj: ");

                //Deklarerar menyvals variabeln.
                int menyVal;

                //Här la jag in TryParse för att snappa upp eventuella fel inmatningar från användaren utan att programmet kraschar.
                Int32.TryParse(Console.ReadLine(), out menyVal);


                switch (menyVal)
                {
                    //Case 1 skapar användaren sina blogginlägg genom att mata in rubrik/titel och därefter inlägget.
                    case 1:
                        //Sparar nya inlägg genom att skapa en ny vektor med plats för 2 element för varje gång.
                        string[] posts = new string[2];
                        //Ber användarens mata in vad hen vill kalla inlägget.
                        Console.WriteLine("\nSkriv in titeln på ditt blogginlägg: \n");
                        //Sparar titeln på första elementet.
                        posts[0] = Console.ReadLine();
                        //Ber användaren att mata in texten på själva inlägget
                        Console.WriteLine("\nSkriv ett inlägg: ");
                        //Sparar inlägg i andra elementet.
                        posts[1] = Console.ReadLine();
                        //Sparar blogginlägget och skriver ut det på skärmen till användaren. // Vi sparar inlägg i listan
                        archive.Add(posts);
                        Console.WriteLine("\n\tDitt blogginlägg är nu sparat!" + "\n\t");
                        Console.WriteLine("\n" + "_______________________________________" + "\n\t");
                        break;

                    //Case 2 tar fram alla inlägg som har skrivits med sin rubrik/titel och innehåll.
                    case 2:
                        //Skriver ut de sparade inläggen på användarens skärm.
                        Console.WriteLine("\nHär är dina sparade inlägg som finns i arkivet, se nedan:  ");
                        //For loopen hjälper oss att bläddra genom varje element
                        for (int i = 0; i < archive.Count; i++)
                        {
                            Console.WriteLine("\nTitel: " + archive[0] + "\n\n" + archive[1]);
                            //Avskärmare av avsikt för ren estetik
                            Console.WriteLine("\n" + "_______________________________________" + "\n\t");
                            Console.ReadLine();
                        }

                        break;

                    // Case 3 kan användaren söka bland sina sparade inlägg i arkivet
                    case 3:
                        //Ber användaren att göra en sökning.
                        Console.WriteLine("Skriv in titeln på det blogginlägg du söker \n");
                        //Skapar en ny sträng variabel som blir sökningen som matas in av användaren.
                        string searchWord = Console.ReadLine();
                        //skapar ytterligare en bool för att göra det enklare för programmet att söka i listan efter det inmatade sökordet.
                        bool sökning = false;
                        //For loopen hjälper oss att bläddra genom varje element.
                        for (int i = 0; i < archive.Count; i++)
                        {   //Använder mig utav en jämförelseoperator.
                            if (archive[0].ToUpper() == searchWord.ToUpper())
                            {
                                //Matchar sökordet och listan så får användaren följande meddelande utskrivet på skärmen.
                                Console.WriteLine("Vi kunde hitta ditt inlägg i arkivet " + archive[0], archive[1]);
                                Console.WriteLine("\nVänligen göra ett nytt menyval.");
                                Console.WriteLine("\n" + "_______________________________________" + "\n\t");
                                sökning = true;
                            }
                            //Om sökordet inte matchar med listan så får användarens följande utskrivet på sin skärm.
                            if (!sökning)
                            {
                                Console.WriteLine("\nDin söknining gav tyvärr inget resultat. " + "\n" + "Antingen har du sökt på ett inlägg som inte finns sparat i arkivet eller så har det blivit fel i inmatningen, vänligen gör ett nytt försök!");
                                break;
                            }
                        }
                        break;

                    //Case 4, Användaren avslutar programmet
                    case 4:
                        //Tackar och bockar, på återseende till användaren.
                        Console.WriteLine("Du har valt att stänga ner programmet, bloggen avslutas. \n\n Ha en fortsatt fin dag så ses vi snart igen!");
                        //Loppen slutar här.
                        ellensBool = false;
                        break;


                    //Om användaren skriver in något som snappas upp av tryparse så vill jag skicka ut ett felmeddelande till användaren för att göra det tydligt hur programmet fungerar.
                    default:
                        Console.WriteLine("ERROR! Vänligen skriv in en siffra mellan 1, 2, 3 och 4 för att göra ett menyval" + "\n" + "För att programmet skall fungera så behöver du försöka igen med en siffra här nedan: " + "\n");
                        break;
                }
            }
            //Vi vill inte att programmet skall stängas ner direkt när den kör igenom programmet så vi anger Console.ReadLine för att ge användaren det aktiva valet att gå vidare i programmet och avsluta när så önskas.
            Console.ReadLine();
        }


    }
}
 
Last edited:
The blog should be a list that can save string arrays. Each individual blog post should be a string array. The vectors must contain at least two elements. NOTE: You may not replace the vector list with a class.
This is a terrible design being imposed on you by teach. Having to remember that index 0 is the title and succeeding indexes are the paragraphs of the post is something you would do in old fashioned procedural programming before object oriented programming became more common. Even modern C programmers would use a struct with a field for the title and then a vector for the paragraphs of the post. I'd love to see a sarcastic comment justifying the choice of data structures saying that it was forced upon you by an out of touch teacher.
 
Anyway to answer your question, look closely at line 89. You are only looking at index 0 instead of index i.
 
Anyway to answer your question, look closely at line 89. You are only looking at index 0 instead of index i.
Thank you for taking the time to help me.

At the beginning of writing the code, I only asked the program to look into i at line 89. Just because that's how I learned to use a linear search from the beginning. It has worked in other codes that I've written but not in this one.

When I removed index 0 and only looked intoi I was not able to use .ToUpper.
I received an error saying:

CS7036: There is no argument given that corresponds to the required formal parameter 'destination' of 'MemoryExtensions.ToUppwe(ReadOnlySpan<char>,Span<char>,CultureInfo?)'

This I didn't understand so I removed the ToUpper and then a new problem came up, I received an error
saying:
CS0019: Operator '==' Cannot be applied to operands of type 'string[]' and 'string'.

Where do I go from here? As I said I have been able to use the code before but in this one, I just can't get it to work.
 
Because of the terrible data structure your teacher is imposing on you, you should try something like:
C#:
 if (archive[i][0].ToUpper() == searchWord.ToUpper())

archive[i] iterates over each "blog post" list item. Recall that each of your "blog post"s is an array of strings. The 0 accesses the first string in the array in the list.

A more readable version would be:
C#:
var blogpost = archive[i];
var title = blogpost[0];
if (title.ToUpper() == searchWord.ToUpper())

Anyway, all of that will only get you exact matches. What you really want is something like:
C#:
var blogpost = archive[i];
var title = blogpost[0];
var words = title.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries); // split on white space, remove empty strings
searchWord = searchWord.ToUpper();
foreach(var word in words)
{
    if (word.ToUpper() == searchWord)
    {
        // do what you want with matching word

        break;    // break out of the loop
    }
}
 
I'm so thankful for your amazing help, I have now managed to get my code running as it should according to the criteria.
Your tips and explanations really helped me to solve this.

Thank you so, so much!
Have a nice day, best regards 😁
 
Back
Top Bottom