简体   繁体   中英

Joining strings together from certain index position C#

My application is reading a line from a text file and then saving this information into my Message class.

I've written the following code, but for the next line in the text file, the message content is longer and needs to be something like split[2] + " " + split[3] + " " + split[4] + " " + split[5] to save the whole message contents.

public Conversation ReadConversation(string inputFilePath)
        {
            try
            {
                var reader = new StreamReader(new FileStream(inputFilePath, FileMode.Open, FileAccess.Read),
                    Encoding.ASCII);

                string conversationName = reader.ReadLine();
                var messages = new List<Message>();

                string line;

                while ((line = reader.ReadLine()) != null)
                {
                    var split = line.Split(' ');

                    string messageContent = split[2] + " " + split[3];


                    messages.Add(new Message(DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(split[0])), split[1], messageContent));

                }

                return new Conversation(conversationName, messages);

As the length of each content varies, I've tried using string messageContent = string.Join(" ", split).

This adds all of the strings together but I need it starting from split[2] and to keep adding the remaining splits for the length of that particular line. Is this possible?

I've tried using string.Join(" ", split, 2, split.count()) with 2 representing the index position I want to start from and count based on the total splits, but I get an error saying: System.ArgumentOutOfRangeException: 'Index and count must refer to a location within the buffer. (Parameter 'startIndex')'

Meaning of string.Join(" ", split, 2, split.count()) this line is read split collection then from starting position 2 join all split collection. For example, if you have string "Hello hi my name is". After splitting it's count will be 5 and starting from position 2 it will try to join all 5. This is why you are getting exception. Instead you can try this string.Join(" ",split,2,split.Count()-2) . Starting from position 2, join all item from collection.

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