|
| 1 | +/*TASK |
| 2 | + * 1 - Using Arrays split user input (string) into userArray |
| 3 | + * 2 - Ask userInput for startIndex and endIndex |
| 4 | + * 3 - Loop userInput for indexes until valid inputs are given, i.e., startIndex > 0 and endIndex < Array.Length |
| 5 | + * 4 - Output subset of userArray |
| 6 | + */ |
| 7 | + |
| 8 | + |
| 9 | +Console.WriteLine("----Welcome to Substrings----\n--Substring using SubString method--\nEnter a string or a phrase :"); |
| 10 | +string userString = Console.ReadLine(); |
| 11 | +string[] userArray = userString.Split(); |
| 12 | + |
| 13 | +// initialize subset indices |
| 14 | +int startIndex = 0; |
| 15 | +int endIndex = 0; |
| 16 | + |
| 17 | +#region option1 - Substring |
| 18 | + |
| 19 | +// iterate user input for substring indices |
| 20 | +try |
| 21 | +{ |
| 22 | + do |
| 23 | + { |
| 24 | + Console.WriteLine("Enter starting index to remove :"); |
| 25 | + startIndex = int.Parse(Console.ReadLine()); |
| 26 | + |
| 27 | + Console.WriteLine("Enter ending index to remove :"); |
| 28 | + endIndex = int.Parse(Console.ReadLine()); |
| 29 | + |
| 30 | + } while (startIndex < 0 && endIndex >= userArray.Length); |
| 31 | +} |
| 32 | +catch(Exception ex) |
| 33 | +{ |
| 34 | + Console.WriteLine("ERROR : " + ex.Message); |
| 35 | +} |
| 36 | +// substring user input |
| 37 | +string subString = userArray[0].Substring(startIndex, endIndex); |
| 38 | +Console.WriteLine($"Current String : {userArray[0]}\nChosen substring : {subString}\n---End Substring---\n"); |
| 39 | + |
| 40 | +#endregion |
| 41 | + |
| 42 | + |
| 43 | +#region option2 - Loop Arrays |
| 44 | + |
| 45 | +// iterate string until required region of substring acquired |
| 46 | +Console.WriteLine("--Substring using FOR loop--\n"); |
| 47 | +string loopResult = ""; |
| 48 | +for (int i = startIndex; i <= endIndex; i++) |
| 49 | +{ |
| 50 | + loopResult += userArray[0][i]; |
| 51 | +} |
| 52 | +Console.WriteLine($"Current String : {userArray[0]}\nChosen Substring : {loopResult}\n---End Loop---\n"); |
| 53 | + |
| 54 | +#endregion |
| 55 | + |
| 56 | + |
| 57 | +#region option3 - LINQ |
| 58 | +// ask user input for which array item to substring |
| 59 | +// split the specific array item -> Array[userChoice].ToCharArray() |
| 60 | +// use LINQ -> Array.Skip(startIndex).Take(endIndex) |
| 61 | + |
| 62 | +#endregion |
| 63 | + |
| 64 | + |
0 commit comments