The string is a sequence of characters including spaces. Objects of String are immutable in java, which means that once an object is created in a string, it’s content cannot be changed. In this particular problem statement, we are given to separate each individual characters from the string provided as the input. Therefore, to separate each character from the string, the individual characters are accessed through its index.
Examples :
Input : string = "GeeksforGeeks" Output: Individual characters from given string : G e e k s f o r G e e k s Input : string = "Characters" Output: Individual characters from given string : C h a r a c t e r s
Approach 1:
- First, define a string.
- Next, create a for-loop where the loop variable will start from index 0 and end at the length of the given string.
- Print the character present at every index in order to separate each individual character.
- For better visualization, separate each individual character by space.
Below is the implementation of the above approach :
// Java Program to Separate the // Individual Characters from a String import java.io.*;
public class GFG {
public static void main(String[] args)
{
String string = "GeeksforGeeks" ;
// Displays individual characters from given string
System.out.println(
"Individual characters from given string: " );
// Iterate through the given string to
// display the individual characters
for ( int i = 0 ; i < string.length(); i++) {
System.out.print(string.charAt(i) + " " );
}
}
} |
Individual characters from given string: G e e k s f o r G e e k s
Time Complexity: O(n), where n is the length of the string.
Approach 2:
- Define a String.
- Use the toCharArray method and store the array of Characters returned in a char array.
- Print separated characters using for-each loop.
Below is the implementation of the above approach :
// Java Implementation of the above approach import java.io.*;
class GFG
{ public static void main(String[] args)
{
// Initialising String
String str = "GeeksForGeeks" ;
// Converts the string into
// char array
char [] arr = str.toCharArray();
System.out.println(
"Displaying individual characters"
+ "from given string:" );
// Printing the characters using for-each loop
for ( char e : arr)
System.out.print(e + " " );
}
} |
Displaying individual charactersfrom given string: G e e k s F o r G e e k s
Time Complexity: O(N)
Space Complexity: O(N)