rcarcia02
rcarcia02

Reputation: 967

Splitting an element of an array

In my C# program (I'm new to C# so I hope that I'm doing things correctly), I'm trying to read in all of the lines from a text file, which will look something along the lines of this, but with more entries (these are fictional people so don't worry about privacy):

Logan Babbleton ID #: 0000011 108 Crest Circle Mr. Logan M. Babbleton 
Pittsburgh PA 15668 SSN: XXX-XX-XXXX
Current Program(s): Bachelor of Science in Cybersecurity
Mr. Carter J. Bairn ID #: 0000012 21340 North Drive Mr. Carter Joseph Bairn 
Pittsburgh PA 15668 SSN: XXX-XX-XXXX
Current Program(s): Bachelor of Science in Computer Science

I have these lines read into an array, concentrationArray and want to find the lines that contain the word "Current", split them at the "(s): " in "Program(s): " and print the words that follow. I've done this earlier in my program, but splitting at an ID instead, like this:

nameLine = nameIDLine.Split(new string[] { "ID" }, StringSplitOptions.None)[1];

However, whenever I attempt to do this, I get an error that my index is out of the bounds of my split array (not my concentrationArray). Here's what I currently have:

for (int i = 0; i < concentrationArray.Length; i++)
{
    if (concentrationArray[i].Contains("Current"))
    {
            lstTest.Items.Add(concentrationArray[i].Split(new string[] { "(s): " }, StringSplitOptions.None)[1]);
    }
}

Where I'm confused is that if I change the index to 0 instead of 1, it will print everything out perfectly, but it will print out the first half, instead of the second half, which is what I want. What am I doing wrong? Any feedback is greatly appreciated since I'm fairly new at C# and would love to learn what I can. Thanks!

Edit - The only thing that I could think of was that maybe sometimes there wasn't anything after the string that I used to separate each element, but when I checked my text file, I found that was not the case and there is always something following the string used to separate.

Upvotes: 2

Views: 192

Answers (4)

Aleksey Dr.
Aleksey Dr.

Reputation: 642

Here is a bit different approach

            List<string> test = new List<string>();
            string pattern = "Current Program(s):";
            string[] allLines = File.ReadAllLines(@"C:\Users\xyz\Source\demo.txt");
            foreach (var line in allLines)
            {
                if (line.Contains(pattern))
                {
                    test.Add(line.Substring(line.IndexOf(pattern) + pattern.Length));
                }
            }

or

        string pattern = "Current Program(s):";
        lstTest.Items.AddRange(File.ReadLines(@"C:\Users\ODuritsyn\Source\demo.xml")
                .Where(line => line.Contains(pattern))
                .Select(line => line.Substring(line.IndexOf(pattern) + pattern.Length)));

Upvotes: 0

Paul
Paul

Reputation: 3306

It is perhaps a little easier to understand and more reusable if you separate the concerns. It will also be easier to test. An example might be...

var allLines = File.ReadLines(@"C:\your\file\path\data.txt");
var currentPrograms = ExtractCurrentPrograms(allLines);

if (currentPrograms.Any())
{
    lstTest.Items.AddRange(currentPrograms);
}

...

private static IEnumerable<string> ExtractCurrentPrograms(IEnumerable<string> lines)
{
    const string targetPhrase = "Current Program(s):";

    foreach (var line in lines.Where(l => !string.IsNullOrWhiteSpace(l)))
    {
        var index = line.IndexOf(targetPhrase);

        if (index >= 0)
        {
            var programIndex = index + targetPhrase.Length;
            var text = line.Substring(programIndex).Trim();

            if (!string.IsNullOrWhiteSpace(text))
            {
                yield return text;
            }
        }
    }
}

Upvotes: 1

Steve
Steve

Reputation: 216243

You should check the result of split before trying to read at index 1.
If your line doesn't contain a "(s): " your code will crash with the exception given

for (int i = 0; i < concentrationArray.Length; i++)
{
    if (concentrationArray[i].Contains("Current"))
    {
         string[] result = concentrationArray[i].Split(new string[] { "(s): " }, StringSplitOptions.None);
         if(result.Length > 1)
             lstTest.Items.Add(result[1]);
         else
             Console.WriteLine($"Line {i} has no (s): followeed by a space");
    }
}

To complete the answer, if you always use index 0 then there is no error because when no separator is present in the input string then the output is an array with a single element containing the whole unsplitted string

Upvotes: 2

Sarmad Aljazrawi
Sarmad Aljazrawi

Reputation: 11

If the line will always starts with

Current Program(s):

then why don't you just replace it with empty string like this:

concentrationArray[i].Replace("Current Program(s): ", "")

Upvotes: 1

Related Questions