-4

I have a string with 3 names(example: string name="Hunter Georgie Martin"). I have 3 tasks for that string:

  1. remove the first name
  2. remove the second name
  3. remove the third name

They don't depend on each other, meaning when deleting first name for the first task it shouldn't also be removed when doing the other tasks.

I completed the first task:

string name = "Hunter Gregorie Martin";//example
string str = name.Substring(name.IndexOf(' ')+1);
Console.WriteLine(str);

The output is what it should be: Gregorie Martin

The problem is that I can't think of a way to finish the other tasks in a similar way.

5
  • Just to give you some hints: Regex (no don't) , IndexOf(String, Int32), ReadonlySpan<char> , string.Split ... the easiest one is probably to split and reassamble ... but that is also not the most efficient one. Commented Jan 27, 2023 at 17:13
  • You don't need to know the names. You get the first " " by indexOf . You can get the second " " with the overload that takes a start-index. Then you basically have all you need. 1: First index+1 to end, 2: start to 1st index + 2nd index+1 to end, and 3: start to second index. Commented Jan 27, 2023 at 17:22
  • string.Split(' ') might help you. But more generally, names are not a solved problem, and in fact are extremely difficult to get right. Commented Jan 27, 2023 at 17:42
  • One thing to note is that you are not removing the string; strings are immutable. Instead, you are creating a new string with the string of interest removed. It costs nearly nothing to keep the original string around (if that makes sense for your solution) Commented Jan 27, 2023 at 17:42
  • @AlexeiLevenkov: Agree. I get regular downvotes when I show a newbie how to loop through a collection looking for the right element, rather than using some whizbang LINQ statement Commented Jan 27, 2023 at 20:09

4 Answers 4

2

This simple function can be used for all three of your examples by utilizing System.Linq.

public string RemoveNameIndexFromString(string name, int indexToRemove, char separator = ' ')
{
    // Split the original string by the separator character
    string[] names = name.Split(separator);

    // Check if the index to remove is valid
    if (indexToRemove < 0 || indexToRemove >= names.Length)
        return "Invalid index";

    // Create a new array with the name at the specified index removed
    var newNames = names.Where((val, idx) => idx != indexToRemove).ToArray();

    // Join the remaining names back together using the separator character
    return string.Join(separator.ToString(), newNames);
}

Usage

Console.WriteLine(RemoveNameIndexFromString("Hunter Gregorie Martin", 0));
Console.WriteLine(RemoveNameIndexFromString("Hunter Gregorie Martin", 1));
Console.WriteLine(RemoveNameIndexFromString("Hunter Gregorie Martin", 2));

Output

Gregorie Martin
Hunter Martin
Hunter Gregorie
Sign up to request clarification or add additional context in comments.

1 Comment

Seting bad example of converting enumerable to array/list for no good reason. Otherwise nice trolling for HW :).
1

Very similar to what GrumpyCrouton (great name!) did, but with a List instead:

  public string RemoveNameIndexFromString(string name, int indexToRemove)
  {
      List<String> names = new List<String>(name.Split(' '));
      if (indexToRemove >=0 && indexToRemove < names.Count) {
        names.RemoveAt(indexToRemove);  
      }
      return String.Join(" ", names);
  }

1 Comment

I actually like this better. Nice!
0

Assuming that you do not want not use fancy C# features and functions, you can do it with Substring and IndexOf alone by applying IndexOf again to the middle name + last name string.

string name = "Hunter Gregorie Martin";
Console.WriteLine("Name = " + name);

int index = name.IndexOf(' ');
string firstName = name.Substring(0, index);
string middleAndLastName = name.Substring(index + 1);

index = middleAndLastName.IndexOf(' ');
string middleName = middleAndLastName.Substring(0, index);
string lastName = middleAndLastName.Substring(index + 1);

Console.WriteLine("First  name removed = " + middleAndLastName);
Console.WriteLine("Middle name removed = " + firstName + " " + lastName);
Console.WriteLine("Last   name removed = " + firstName + " " + middleName);

prints

Name = Hunter Gregorie Martin
First  name removed = Gregorie Martin
Middle name removed = Hunter Martin
Last   name removed = Hunter Gregorie

Just be creative!

Comments

-1

Riff on GrumpyCrouton's answer using Take and Skip (taking all items before desired index and concatenating with items after the index) instead of Where (which skips the item). Also packing everything into single statements using IIFE as many people are concerned about number of statements (vs. readability)

string RemoveNameIndexFromString(string v, int idx) => 
    ((Func<string[], string>)(r => 
        String.Join(" ",r.Take(idx).Concat(r.Skip(idx+1)))))(v.Split());

Less crazy version without IIFE would need to split twice but more readable:

string RemoveNameIndexFromString(string v, int idx) => 
    String.Join(" ",v.Split().Take(idx).Concat(v.Split().Skip(idx+1)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.