Different Ways to Print First K Characters of the String in Java
Last Updated :
30 Aug, 2020
Given a string str and a positive integer k, the task is to write a Java program to print the first k characters of the string. If the length of the string is less than k then print the string as it is.
Examples:
Input: str = “GeeksForGeeks”, k = 5
Output: Geeks
Explanation: The first k characters of the given string is ‘Geeks’.
Input: str = “Geeks”, k = 6
Output: Geeks
Explanation: The length of the given string is less than k. Therefore, we print the string as it is.
Method 1: Using string length
- Get the string and a positive integer k to print the first k characters of the string.
- Check if the string is null or empty then return null.
- Check if the string length is greater than k then get the first k characters of the string using str.substring(0, k).
- If the string length is less than k then return the string as it is.
- Now, print the first k characters of the string.
Below is the implementation of the above approach:
Java
class GFG {
public static String
firstKCharacters(String str, int k)
{
if (str == null || str.isEmpty())
return null ;
if (str.length() > k)
return str.substring( 0 , k);
else
return str;
}
public static void main(String args[])
{
String str = "GeeksForGeeks" ;
int k = 5 ;
System.out.println(
firstKCharacters(str, k));
}
}
|
Method 2: Without checking the size
- The idea is to use Math.min() function as an end index of the substring method.
- Find the minimum value between the length of the string and positive integer k.
- Get the substring from zero to the minimum of string length and k.
- Now, print the first k characters of the string.
Below is the implementation of the above approach:
Java
class GFG {
public static String firstKCharacters(String str, int k)
{
if (str == null || str.isEmpty())
return null ;
return str.substring( 0 , Math.min(str.length(), k));
}
public static void main(String args[])
{
String str = "GeeksForGeeks" ;
int k = 5 ;
System.out.println(firstKCharacters(str, k));
}
}
|
Share your thoughts in the comments
Please Login to comment...