FAQ: Working with Text - Get Parts of Strings

Oh my!!! This is a horrible way to teach this lesson. I spent so much time wondering “if I already know the position of the thing I want (the first letter), why would write code to look for the letter to return the position so that I can, in turn, return the letter?” Do you see how confusing that is!?

Yes, it is important to know how to use those tools, absolutely agree. But this lesson shows a method that is simply illogical and bad code. Please find another example to better highlight the importance and use of these tools.

1 Like

Lmao, had a some with this one, but after tinkering with it I finally got it… I think.

using System;

namespace NameGrab
{
  class Program
  {
    static void Main(string[] args)
    {
      // User Name
      string name = "Farhad Hesam Abbasi";

      // Get first letter
      int charPosition = name.IndexOf("F"); //Saves 0 to charPosition 
      char firstLetter = name[charPosition]; //returns "F"

      // Get last name
      int stringPosition = name.IndexOf("Abbasi"); //Saves 13 to stringPosition
      string lastName = name.Substring(stringPosition); //returns "Abbasi"

      // Print results
      Console.WriteLine(firstLetter + ". " + lastName); //Prints "F Abbasi"
    }
  }
}
using System;

namespace NameGrab
{
  class Program
  {
    static void Main(string[] args)
    {
      // User Name
      string name = "Farhad Hesam Abbasi";

      // Get first letter
char firstLetter = name[0];
int fPosition = name.IndexOf(firstLetter);
      
      // Get last name
      
int position = name.IndexOf("Abbasi");
      string lastName = name.Substring(name);

      // Print results


    }
  }
}

What going on here?
Program.cs(19,40): error CS1503: Argument 1: cannot convert from ‘string’ to ‘int’ [/home/ccuser/workspace/csharp-working-with-text-get-parts-of-strings/e7-workspace.csproj]

The build failed. Fix the build errors and run again.

CODE PASSED WITH THIS IN THE CONSOLE!

Hello, @lilrock.

In the code above what is the value assigned to name?
Substring() is expecting at least one int argument. It will return part of the string that it is invoked on starting at the index provided as an argument.
For example:

string me = "midlindner";
string last = me.Substring(3);
Console.WriteLine(last); //lindner

Could we expect the following to work?

string me = "midlindner";
string last = me.Substring(me); //same as writing me.Substring("midlindner")

The above would produce the same error that you have. The Substring() method is expecting an int, but I’ve provided a string.