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’.
- 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 last characters 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);
}
}
|
- 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);
}
}
|
Time complexity: O(1)
Auxiliary space: O(n) because it is using extra space for charArray
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
13 Dec, 2022
Like Article
Save Article