The index of the first character in a string is 0 while the index of the last character is length

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a string str, the task is to print the first and the last character of the string.

    Examples:

    Input: str = “GeeksForGeeks”

    Output:

    First: G

    Last: s

    Explanation: The first character of the given string is ‘G’ and the last character of given string is ‘s’.

    Input: str = “Java”

    Output: 

    First: J

    Last: a

    Explanation: The first character of given string is ‘J’ and the last character of given string is ‘a’.

    Method 1: Using String.charAt() method

    • The idea is to use charAt() method of String class to find the first and last character in a string. 
    • The charAt() method accepts a parameter as an index of the character to be returned.
    • The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .
    • Now, print the first and the last character of the string.

    Below is the implementation of the above approach:

    Java

    class GFG {

        public static void

        firstAndLastCharacter(String str)

        {

            int n = str.length();

            char first = str.charAt(0);

            char last = str.charAt(n - 1);

            System.out.println("First: " + first);

            System.out.println("Last: " + last);

        }

        public static void main(String args[])

        {

            String str = "GeeksForGeeks";

            firstAndLastCharacter(str);

        }

    }

    Method 2: Using String.toCharArray() method

    • The idea is to first convert the given string into a character array using toCharArray() method of String class, then find the first and last character of a string and print it.

    Below is the implementation of the above approach:

    Java

    class GFG {

        public static void

        firstAndLastCharacter(String str)

        {

            char[] charArray = str.toCharArray();

            int n = charArray.length;

            char first = charArray[0];

            char last = charArray[n - 1];

            System.out.println("First: " + first);

            System.out.println("Last: " + last);

        }

        public static void main(String args[])

        {

            String str = "GeeksForGeeks";

            firstAndLastCharacter(str);

        }

    }


    Skip to main content

    This browser is no longer supported.

    Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

    String.Substring Method

    • Reference

    Definition

    Retrieves a substring from this instance.

    This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

    In this article

    Overloads

    Substring(Int32)

    Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

    Substring(Int32, Int32)

    Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

    Substring(Int32)

    Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

    public: System::String ^ Substring(int startIndex);public string Substring (int startIndex);member this.Substring : int -> stringPublic Function Substring (startIndex As Integer) As String

    Parameters

    startIndex Int32

    The zero-based starting character position of a substring in this instance.

    Returns

    String

    A string that is equivalent to the substring that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance.

    Exceptions

    startIndex is less than zero or greater than the length of this instance.

    Examples

    The following example demonstrates obtaining a substring from a string.

    using namespace System; using namespace System::Collections; int main() { array^info = { "Name: Felica Walker", "Title: Mz.", "Age: 47", "Location: Paris", "Gender: F"}; int found = 0; Console::WriteLine("The initial values in the array are:"); for each (String^ s in info) Console::WriteLine(s); Console::WriteLine("\nWe want to retrieve only the key information. That is:"); for each (String^ s in info) { found = s->IndexOf(": "); Console::WriteLine(" {0}", s->Substring(found + 2)); } } // The example displays the following output: // The initial values in the array are: // Name: Felica Walker // Title: Mz. // Age: 47 // Location: Paris // Gender: F // // We want to retrieve only the key information. That is: // Felica Walker // Mz. // 47 // Paris // F string [] info = { "Name: Felica Walker", "Title: Mz.", "Age: 47", "Location: Paris", "Gender: F"}; int found = 0; Console.WriteLine("The initial values in the array are:"); foreach (string s in info) Console.WriteLine(s); Console.WriteLine("\nWe want to retrieve only the key information. That is:"); foreach (string s in info) { found = s.IndexOf(": "); Console.WriteLine(" {0}", s.Substring(found + 2)); } // The example displays the following output: // The initial values in the array are: // Name: Felica Walker // Title: Mz. // Age: 47 // Location: Paris // Gender: F // // We want to retrieve only the key information. That is: // Felica Walker // Mz. // 47 // Paris // F let info = [| "Name: Felica Walker"; "Title: Mz." "Age: 47"; "Location: Paris"; "Gender: F" |] printfn "The initial values in the array are:" for s in info do printfn $"{s}" printfn "\nWe want to retrieve only the key information. That is:" for s in info do let found = s.IndexOf ": " printfn $" {s.Substring(found + 2)}" // The example displays the following output: // The initial values in the array are: // Name: Felica Walker // Title: Mz. // Age: 47 // Location: Paris // Gender: F // // We want to retrieve only the key information. That is: // Felica Walker // Mz. // 47 // Paris // F Public Class SubStringTest Public Shared Sub Main() Dim info As String() = { "Name: Felica Walker", "Title: Mz.", "Age: 47", "Location: Paris", "Gender: F"} Dim found As Integer = 0 Console.WriteLine("The initial values in the array are:") For Each s As String In info Console.WriteLine(s) Next s Console.WriteLine(vbCrLf + "We want to retrieve only the key information. That is:") For Each s As String In info found = s.IndexOf(": ") Console.WriteLine(" {0}", s.Substring(found + 2)) Next s End Sub End Class ' The example displays the following output: ' The initial values in the array are: ' Name: Felica Walker ' Title: Mz. ' Age: 47 ' Location: Paris ' Gender: F ' ' We want to retrieve only the key information. That is: ' Felica Walker ' Mz. ' 47 ' Paris ' F

    The following example uses the Substring method to separate key/value pairs that are delimited by an equals ("=") character.

    String[] pairs = { "Color1=red", "Color2=green", "Color3=blue", "Title=Code Repository" }; foreach (var pair in pairs) { int position = pair.IndexOf("="); if (position < 0) continue; Console.WriteLine("Key: {0}, Value: '{1}'", pair.Substring(0, position), pair.Substring(position + 1)); } // The example displays the following output: // Key: Color1, Value: 'red' // Key: Color2, Value: 'green' // Key: Color3, Value: 'blue' // Key: Title, Value: 'Code Repository' let pairs = [| "Color1=red"; "Color2=green"; "Color3=blue" "Title=Code Repository" |] for pair in pairs do let position = pair.IndexOf "=" if position >= 0 then printfn $"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'" // The example displays the following output: // Key: Color1, Value: 'red' // Key: Color2, Value: 'green' // Key: Color3, Value: 'blue' // Key: Title, Value: 'Code Repository' Module Example Public Sub Main() Dim pairs() As String = { "Color1=red", "Color2=green", "Color3=blue", "Title=Code Repository" } For Each pair In pairs Dim position As Integer = pair.IndexOf("=") If position < 0 then Continue For Console.WriteLine("Key: {0}, Value: '{1}'", pair.Substring(0, position), pair.Substring(position + 1)) Next End Sub End Module ' The example displays the following output: ' Key: Color1, Value: 'red' ' Key: Color2, Value: 'green' ' Key: Color3, Value: 'blue' ' Key: Title, Value: 'Code Repository'

    The IndexOf method is used to get the position of the equals character in the string. The call to the Substring(Int32, Int32) method extracts the key name, which starts from the first character in the string and extends for the number of characters returned by the call to the IndexOf method. The call to the Substring(Int32) method then extracts the value assigned to the key. It starts at one character position beyond the equals character and extends to the end of the string.

    Remarks

    You call the Substring(Int32) method to extract a substring from a string that begins at a specified character position and ends at the end of the string. The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. To extract a substring that begins at a specified character position and ends before the end of the string, call the Substring(Int32, Int32) method.

    Note

    This method does not modify the value of the current instance. Instead, it returns a new string that begins at the startIndex position in the current string.

    To extract a substring that begins with a particular character or character sequence, call a method such as IndexOf or IndexOf to get the value of startIndex. The second example illustrates this; it extracts a key value that begins one character position after the "=" character.

    If startIndex is equal to zero, the method returns the original string unchanged.

    See also

    • Int32
    • Concat(Object)
    • Insert(Int32, String)
    • Join(String, String[])
    • Remove(Int32, Int32)
    • Replace(Char, Char)
    • Split(Char[])
    • Trim(Char[])

    Applies to

    Substring(Int32, Int32)

    Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

    public: System::String ^ Substring(int startIndex, int length);public string Substring (int startIndex, int length);member this.Substring : int * int -> stringPublic Function Substring (startIndex As Integer, length As Integer) As String

    Parameters

    startIndex Int32

    The zero-based starting character position of a substring in this instance.

    length Int32

    The number of characters in the substring.

    Returns

    String

    A string that is equivalent to the substring of length length that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance and length is zero.

    Exceptions

    startIndex plus length indicates a position not within this instance.

    -or-

    startIndex or length is less than zero.

    Examples

    The following example illustrates a simple call to the Substring(Int32, Int32) method that extracts two characters from a string starting at the sixth character position (that is, at index five).

    String value = "This is a string."; int startIndex = 5; int length = 2; String substring = value.Substring(startIndex, length); Console.WriteLine(substring); // The example displays the following output: // is let value = "This is a string." let startIndex = 5 let length = 2 let substring = value.Substring(startIndex, length) printfn $"{substring}" // The example displays the following output: // is Module Example Public Sub Main() Dim value As String = "This is a string." Dim startIndex As Integer = 5 Dim length As Integer = 2 Dim substring As String = value.Substring(startIndex, length) Console.WriteLine(substring) End Sub End Module ' The example displays the following output: ' is

    The following example uses the Substring(Int32, Int32) method in the following three cases to isolate substrings within a string. In two cases the substrings are used in comparisons, and in the third case an exception is thrown because invalid parameters are specified.

    • It extracts the single character and the third position in the string (at index 2) and compares it with a "c". This comparison returns true.

    • It extracts zero characters starting at the fourth position in the string (at index 3) and passes it to the IsNullOrEmpty method. This returns true because the call to the Substring method returns String.Empty.

    • It attempts to extract one character starting at the fourth position in the string. Because there is no character at that position, the method call throws an ArgumentOutOfRangeException exception.

    string myString = "abc"; bool test1 = myString.Substring(2, 1).Equals("c"); // This is true. Console.WriteLine(test1); bool test2 = string.IsNullOrEmpty(myString.Substring(3, 0)); // This is true. Console.WriteLine(test2); try { string str3 = myString.Substring(3, 1); // This throws ArgumentOutOfRangeException. Console.WriteLine(str3); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); } // The example displays the following output: // True // True // Index and length must refer to a location within the string. // Parameter name: length let myString = "abc" let test1 = myString.Substring(2, 1).Equals "c" // This is true. printfn $"{test1}" let test2 = String.IsNullOrEmpty(myString.Substring(3, 0)) // This is true. printfn $"{test2}" try let str3 = myString.Substring(3, 1) // This throws ArgumentOutOfRangeException. printfn $"{str3}" with :? ArgumentOutOfRangeException as e -> printfn $"{e.Message}" // The example displays the following output: // True // True // Index and length must refer to a location within the string. // Parameter name: length Public Class Sample Public Shared Sub Main() Dim myString As String = "abc" Dim test1 As Boolean = myString.Substring(2, 1).Equals("c") ' This is true. Console.WriteLine(test1) Dim test2 As Boolean = String.IsNullOrEmpty(myString.Substring(3, 0)) ' This is true. Console.WriteLine(test2) Try Dim str3 As String = myString.Substring(3, 1) ' This throws ArgumentOutOfRangeException. Console.WriteLine(str3) Catch e As ArgumentOutOfRangeException Console.WriteLIne(e.Message) End Try End Sub End Class ' The example displays the following output: ' True ' True ' Index and length must refer to a location within the string. ' Parameter name: length

    The following example uses the Substring method to separate key/value pairs that are delimited by an equals ("=") character.

    String[] pairs = { "Color1=red", "Color2=green", "Color3=blue", "Title=Code Repository" }; foreach (var pair in pairs) { int position = pair.IndexOf("="); if (position < 0) continue; Console.WriteLine("Key: {0}, Value: '{1}'", pair.Substring(0, position), pair.Substring(position + 1)); } // The example displays the following output: // Key: Color1, Value: 'red' // Key: Color2, Value: 'green' // Key: Color3, Value: 'blue' // Key: Title, Value: 'Code Repository' let pairs = [| "Color1=red"; "Color2=green"; "Color3=blue" "Title=Code Repository" |] for pair in pairs do let position = pair.IndexOf "=" if position >= 0 then printfn $"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'" // The example displays the following output: // Key: Color1, Value: 'red' // Key: Color2, Value: 'green' // Key: Color3, Value: 'blue' // Key: Title, Value: 'Code Repository' Module Example Public Sub Main() Dim pairs() As String = { "Color1=red", "Color2=green", "Color3=blue", "Title=Code Repository" } For Each pair In pairs Dim position As Integer = pair.IndexOf("=") If position < 0 then Continue For Console.WriteLine("Key: {0}, Value: '{1}'", pair.Substring(0, position), pair.Substring(position + 1)) Next End Sub End Module ' The example displays the following output: ' Key: Color1, Value: 'red' ' Key: Color2, Value: 'green' ' Key: Color3, Value: 'blue' ' Key: Title, Value: 'Code Repository'

    The IndexOf method is used to get the position of the equals character in the string. The call to the Substring(Int32, Int32) method extracts the key name, which starts from the first character in the string and extends for the number of characters returned by the call to the IndexOf method. The call to the Substring(Int32) method then extracts the value assigned to the key. It starts at one character position beyond the equals character and extends to the end of the string.

    Remarks

    You call the Substring(Int32, Int32) method to extract a substring from a string that begins at a specified character position and ends before the end of the string. The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. To extract a substring that begins at a specified character position and continues to the end of the string, call the Substring(Int32) method.

    Note

    This method does not modify the value of the current instance. Instead, it returns a new string with length characters starting from the startIndex position in the current string.

    The length parameter represents the total number of characters to extract from the current string instance. This includes the starting character found at index startIndex. In other words, the Substring method attempts to extract characters from index startIndex to index startIndex + length - 1.

    To extract a substring that begins with a particular character or character sequence, call a method such as IndexOf or LastIndexOf to get the value of startIndex.

    If the substring extends from startIndex to a specified character sequence, you can call a method such as IndexOf or LastIndexOf to get the index of the ending character or character sequence. You can then convert that value to an index position in the string as follows:

    • If you've searched for a single character that is to mark the end of the substring, the length parameter equals endIndex - startIndex + 1, where endIndex is the return value of the IndexOf or IndexOf method. The following example extracts a continuous block of "b" characters from a string.

      String s = "aaaaabbbcccccccdd"; Char charRange = 'b'; int startIndex = s.IndexOf(charRange); int endIndex = s.LastIndexOf(charRange); int length = endIndex - startIndex + 1; Console.WriteLine("{0}.Substring({1}, {2}) = {3}", s, startIndex, length, s.Substring(startIndex, length)); // The example displays the following output: // aaaaabbbcccccccdd.Substring(5, 3) = bbb let s = "aaaaabbbcccccccdd" let charRange = 'b' let startIndex = s.IndexOf charRange let endIndex = s.LastIndexOf charRange let length = endIndex - startIndex + 1 printfn $"{s}.Substring({startIndex}, {length}) = {s.Substring(startIndex, length)}" // The example displays the following output: // aaaaabbbcccccccdd.Substring(5, 3) = bbb Module Example Public Sub Main() Dim s As String = "aaaaabbbcccccccdd" Dim charRange As Char = "b"c Dim startIndex As Integer = s.Indexof(charRange) Dim endIndex As Integer = s.LastIndexOf(charRange) Dim length = endIndex - startIndex + 1 Console.WriteLine("{0}.Substring({1}, {2}) = {3}", s, startIndex, length, s.Substring(startIndex, length)) End Sub End Module ' The example displays the following output: ' aaaaabbbcccccccdd.Substring(5, 3) = bbb
    • If you've searched for multiple characters that are to mark the end of the substring, the length parameter equals endIndex + endMatchLength - startIndex, where endIndex is the return value of the IndexOf or IndexOf method, and endMatchLength is the length of the character sequence that marks the end of the substring. The following example extracts a block of text that contains an XML element.

      String s = "extantstill in existence"; String searchString = ""; int startIndex = s.IndexOf(searchString); searchString = "extantstill in existence // Substring; still in existence let s = "extantstill in existence" let searchString = "" let startIndex = s.IndexOf(searchString) let searchString = "extantstill in existence // Substring; still in existence Module Example Public Sub Main() Dim s As String = "extantstill in existence" Dim searchString As String = "" Dim startindex As Integer = s.IndexOf(searchString) searchString = "extantstill in existence ' Substring; still in existence
    • If the character or character sequence is not included in the end of the substring, the length parameter equals endIndex - startIndex, where endIndex is the return value of the IndexOf or IndexOf method.

    If startIndex is equal to zero and equals the length of the current string, the method returns the original string unchanged.

    See also

    • Remove(Int32, Int32)
    • Replace(Char, Char)
    • Trim(Char[])

    Applies to

    How do I find the first and last index of a string?

    The lastIndexOf() method returns the position of the last occurrence of specified character(s) in a string. Tip: Use the indexOf method to return the position of the first occurrence of specified character(s) in a string.

    How do you index a character in a string?

    You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1 . For example, the following code gets the character at index 9 in a string: String anotherPalindrome = "Niagara.

    How do you find the last index of a string?

    The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).

    How do you get the index of the first occurrence of character O in string hello how are you?

    The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.