简体   繁体   中英

How can I have a .txt file that I read lines from and put them into an array, but every line is split after a certain character

I'm making a console app to navigate my PC.

I have a function called Askforcmd() which lets you write a command. It tests if you wrote a specific thing with ifs and else ifs (what you write is stored in the string "commands").

I'm trying to write all my games in a .txt, seperated by newline, and write the location after (seperated by "^"), (example:

portal 2^C:/PathOfGame

portal^C:/path

) and have the code know that if you write the name of a game, it should open the file at the path after (I know how to open the file).

I know how to read from a txt and put that in an array, but how do I make it stop reading the lines after a certain character and store that in a different array? What I have so far:

else if (lines.Any(commands.Contains))
        {
           /*Code to check what game to open and at 
             what path
           */
          Askforcmd();
        }

else if (commands == "games")
        {
            Console.Write("\n");
            int count = lines.Length;
            int numsss = 0;
            int ds;
            while (numsss != count)
            {
                ds = numsss + 1;
                Console.WriteLine(ds + ": " + lines[numsss]);

                numsss++;
            }
            Askforcmd();
        }

When I run the code and write "games", it lists the games with a number before them.

1: Portal 2

2: Portal

etc

You can take the first string you read and run the split command on it.

Array[] newArray = lines[numsss].split('^');

you would get a new array equal to the file name and the path is in the second element.

edit: As per your comment, you have weird requirements. You could do something like this:

//assume your previous array is lines
List<string> temp = new List<string>;
for each (string line in lines)
{

    temp.Add(line.split('^')[0]);
    temp.Add(line.split('^')[1]);
}
String[] outArray = temp.toArray();

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