Java is one of the most popular programming languages used in software development. One of the common tasks that a Java developer needs to perform is to print the first k characters of a given string. There are different ways to achieve this, and in this article, we will explore some of them.
The substring() method is a built-in function in Java that returns a part of the given string. We can use this method to extract the first k characters of a string as shown in the code snippet below:
String str = "Hello World"; int k = 5; String firstKChars = str.substring(0, k); System.out.println(firstKChars);
Output:
Hello
The charAt() method is another built-in function in Java that returns the character at a specified index in a string. We can use this method to iterate through the first k characters of a string and print them as shown in the code snippet below:
String str = "Hello World"; int k = 5; for (int i = 0; i < k; i++) { System.out.print(str.charAt(i)); }
Output:
Hello
The toCharArray() method is a built-in function in Java that converts a string to an array of characters. We can use this method to extract the first k characters of a string as shown in the code snippet below:
String str = "Hello World"; int k = 5; char[] charArray = str.toCharArray(); for (int i = 0; i < k; i++) { System.out.print(charArray[i]); }
Output:
Hello
We can combine the substring() and toCharArray() methods to extract the first k characters of a string as an array of characters as shown in the code snippet below:
String str = "Hello World"; int k = 5; char[] charArray = str.substring(0, k).toCharArray(); for (char c : charArray) { System.out.print(c); }
Output:
Hello