locked
How to Extract values with indexof and substring? RRS feed

  • Question

  • In the console I'm trying to get the code to prompt for questions (first name:, etc.) and for me to be able to fill those questions accordingly. Nothing shows up in the console message and it just crashes. I assume it's because I'm using the indexof and substring methods incorrectly. 

    Does anyone know how to make the console prompt for the questions and for it to extract the values properly?

    I know I can do the split method, but I'm actually submitting this to an automated grader which does not support the split method

    Code is below

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ProgrammingAssignment1
    {
        /// <summary>
        /// A class holding personal data for a person
        /// </summary>
        public class PersonalData
        {
            #region Fields
    
            // declare your fields here
            
    
            public string firstName;
            public string middleName;
            public string lastName;
            public string streetAddress;
            public string city;
            public string state;
            public string postalCode;
            public string country;
            public string phoneNumber;
            #endregion
    
            #region Properties
    
            /// <summary>
            /// Gets the person's first name
            /// </summary>
            public string FirstName
            {
                get 
                {
                    // delete code below and replace with correct code
                    { return firstName; }
                }
            }
    
            /// <summary>
            /// Gets the person's middle name
            /// </summary>
            public string MiddleName
            {
                get
                {
                    // delete code below and replace with correct code
                    return middleName;
                }
            }
    
            /// <summary>
            /// Gets the person's last name
            /// </summary>
            public string LastName
            {
                get
                {
                    // delete code below and replace with correct code
                    return lastName;
                }
            }
    
            /// <summary>
            /// Gets the person's street address
            /// </summary>
            public string StreetAddress
            {
                get
                {
                    // delete code below and replace with correct code
                    return streetAddress;
                }
            }
    
            /// <summary>
            /// Gets the person's city or town
            /// </summary>
            public string City
            {
                get
                {
                    // delete code below and replace with correct code
                    return city;
                }
            }
    
            /// <summary>
            /// Gets the person's state or province
            /// </summary>
            public string State
            {
                get
                {
                    // delete code below and replace with correct code
                    return state;
                }
            }
    
            /// <summary>
            /// Gets the person's postal code
            /// </summary>
            public string PostalCode
            {
                get
                {
                    // delete code below and replace with correct code
                    return postalCode;
                }
            }
    
            /// <summary>
            /// Gets the person's country
            /// </summary>
            public string Country
            {
                get
                {
                    // delete code below and replace with correct code
                    return country;
                }
            }
    
            /// <summary>
            /// Gets the person's phone number (digits only, no 
            /// parentheses, spaces, or dashes)
            /// </summary>
            public string PhoneNumber
            {
                get
                {
                    // delete code below and replace with correct code
                    return phoneNumber;
                }
            }
    
            #endregion
    
            #region Constructor
    
            /// <summary>
            /// Constructor
            /// Reads personal data from a file. If the file
            /// read fails, the object contains an empty string for all
            /// the personal data
            /// </summary>
            /// <param name="fileName">name of file holding personal data</param>
            public PersonalData(string fileName)
            {
                // your code can assume we know the order in which the
                // values appear in the string; it's the same order as
                // they're listed for the properties above. We could do 
                // something more complicated with the names and values, 
                // but that's not necessary here
    
                StreamReader input = null;
    
                try
                {
                    input = File.OpenText(fileName);
                    string names = input.ReadLine();
                }
    
                catch (Exception e)
                {
    
                }
    
                finally
                {
                    if (input != null)
                    {
                        input.Close();
                    }
    
                }
    
                // IMPORTANT: The mono compiler the automated grader uses
                // does NOT support the string Split method. You have to 
                // use the IndexOf method to find comma locations and the
                // Substring method to chop off the front of the string
                // after you extract each value to extract and save the
                // personal data
                Console.Write("Enter first name, middle name, last name, street address, city, state, postal code, country, phone number");
                string csvString = Console.ReadLine();
    
                int commaLocation = csvString.IndexOf(',');
    
                string firstName = csvString.Substring(0, commaLocation);
                string middleName = csvString.Substring(commaLocation + 1);
                string lastName = csvString.Substring(commaLocation + 2);
                string streetAddress = csvString.Substring(commaLocation + 3);
                string city = csvString.Substring(commaLocation + 4);
                string state = csvString.Substring(commaLocation + 5);
                string postalCode = csvString.Substring(commaLocation + 6);
                string country = csvString.Substring(commaLocation + 7);
                string phoneNumber = csvString.Substring(commaLocation + 8);
    
                Console.WriteLine();
                Console.WriteLine("First Name: " + firstName);
                Console.WriteLine("Middle Name: " + middleName);
                Console.WriteLine("Last Name: " + lastName);
                Console.WriteLine("Street Address: " + streetAddress);
                Console.WriteLine("City: " + city);
                Console.WriteLine("State: " + state);
                Console.WriteLine("Postal Code: " + postalCode);
                Console.WriteLine("Country: " + country);
                Console.WriteLine("Phone Number: " + phoneNumber);
    
                Console.WriteLine();
    
            }
    
            #endregion
        }
    }



    • Edited by YooOwnIt Sunday, August 30, 2020 9:06 PM
    Sunday, August 30, 2020 9:05 PM

All replies

  • Hello,

    Beings you are expecting all information on one line use split homebrewed rather than indexof. Split will give you are comma delimited string array. Once split check the length of the string array to ensure there are elements for each piece of information you are interested in then store the information by indexing into the string array. 

    Short and simple to work from.

    using System;
    using System.Collections.Generic;
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                var userInfo = SplitString(Console.ReadLine(), ',');
    
                if (userInfo.Length == 3)
                {
                    var person = new Person {FirstName = userInfo[0], MiddleName = userInfo[1], LastName = userInfo[2]};
                    Console.WriteLine(person);
                }
                else
                {
                    Console.WriteLine("Not enough information");
                }
    
                Console.ReadLine();
    
            }
    
            public static string[] SplitString(string input, char delimiter)
            {
                var parts = new List<string>();
                int start = 0;
                for (int index = 0; index < input.Length; index++)
                {
                    if (input[index] == delimiter)
                    {
                        parts.Add(input.Substring(start, index - start));
                        start = index + 1;
                    }
                }
                parts.Add(input.Substring(start, input.Length - start));
                return parts.ToArray();
            }
            class Person
            {
                public string FirstName { get; set; }
                public string MiddleName { get; set; }
                public string LastName { get; set; }
    
                public override string ToString() => $"{FirstName} {MiddleName} {LastName}";
            }
        }
    }
    


    And this is bad to have an empty catch, if you had an error it's unknown.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange


    Sunday, August 30, 2020 10:20 PM
  • Thanks for the solution, I'll try it out! The problem is though the automated grader  does not support the split string method so it'll probably fail all the test cases
    Monday, August 31, 2020 2:15 AM
  • Hi YooOwnlt,

    Thank you for posting here.

    If you can't use String.Split(), you can consider writing a custom method to split it.

            public static String[] Split(String txt, char[] delim)
            {
                if (txt == null)
                    return new String[0]; // or exception
                if (delim == null || delim.Length == 0)
                    return new String[0]; // or exception
    
                char[] text = txt.ToCharArray();
                string[] result = new string[1]; 
                int part = 0;
                int itemInArray = 1;
    
                for (int i = 0; i < text.Length; i++)
                {
                    if (IsIn(delim, text[i]))
                    {
                        Array.Resize(ref result, ++itemInArray); 
                        part++;
                    }
                    else
                        result[part] += text[i];
                }
                return result;
            }
            public static Boolean IsIn(char[] delim, char c)
            {
                for (int i = 0; i < delim.Length; i++)
                    if (c == delim[i])
                        return true;
                return false;
            }

                Console.WriteLine("Enter first name, middle name, last name");
                string csvString = Console.ReadLine();
    
                String[] re = Split(csvString, new char[] { ',' });
    
                string firstName = re[0];
                string middleName = re[1];
                string lastName = re[2];
               
    
                Console.WriteLine("First Name: " + firstName);
                Console.WriteLine("Middle Name: " + middleName);
                Console.WriteLine("Last Name: " + lastName);

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, August 31, 2020 8:11 AM