给定一个字符串str,任务是打印第一和字符串的最后一个字符。
例子:
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’.
方法一:使用 String.charAt() 方法
- 我们的想法是使用String类的charAt()方法来查找字符串的第一个和最后一个字符。
- charAt()方法接受一个参数作为要返回的字符的索引。
- 在一个字符串的第一个字符是存在于索引零并在字符串的最后一个字符存在于字符串-1的索引长度。
- 现在,打印字符串的第一个和最后一个字符。
下面是上述方法的实现:
Java
// Java program to find first
// and last character of a string
class GFG {
// Function to print first and last
// character of a string
public static void
firstAndLastCharacter(String str)
{
// Finding string length
int n = str.length();
// First character of a string
char first = str.charAt(0);
// Last character of a string
char last = str.charAt(n - 1);
// Printing first and last
// character of a string
System.out.println("First: " + first);
System.out.println("Last: " + last);
}
// Driver Code
public static void main(String args[])
{
// Given string str
String str = "GeeksForGeeks";
// Function Call
firstAndLastCharacter(str);
}
}
Java
// Java program to find first
// and last character of a string
class GFG {
// Function to print first and last
// character of a string
public static void
firstAndLastCharacter(String str)
{
// Converting a string into
// a character array
char[] charArray = str.toCharArray();
// Finding the length of
// character array
int n = charArray.length;
// First character of a string
char first = charArray[0];
// Last character of a string
char last = charArray[n - 1];
// Printing first and last
// character of a string
System.out.println("First: " + first);
System.out.println("Last: " + last);
}
// Driver Code
public static void main(String args[])
{
// Given string str
String str = "GeeksForGeeks";
// Function Call
firstAndLastCharacter(str);
}
}
输出:
First: G
Last: s
方法 2:使用 String.toCharArray() 方法
- 我们的想法是先转换给定的字符串转换成使用String类的toCharArray()方法的字符数组,然后找到一个字符串的第一个和最后一个字符和打印。
下面是上述方法的实现:
Java
// Java program to find first
// and last character of a string
class GFG {
// Function to print first and last
// character of a string
public static void
firstAndLastCharacter(String str)
{
// Converting a string into
// a character array
char[] charArray = str.toCharArray();
// Finding the length of
// character array
int n = charArray.length;
// First character of a string
char first = charArray[0];
// Last character of a string
char last = charArray[n - 1];
// Printing first and last
// character of a string
System.out.println("First: " + first);
System.out.println("Last: " + last);
}
// Driver Code
public static void main(String args[])
{
// Given string str
String str = "GeeksForGeeks";
// Function Call
firstAndLastCharacter(str);
}
}
输出:
First: G
Last: s
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live