The Wayback Machine - https://web.archive.org/web/20240905002330/https://www.geeksforgeeks.org/java-program-to-separate-the-individual-characters-from-a-string/
Open In App

Java Program to Separate the Individual Characters from a String

Last Updated : 27 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  1. First, define a string.
  2. Next, create a for-loop where the loop variable will start from index 0 and end at the length of the given string.
  3. Print the character present at every index in order to separate each individual character.
  4. For better visualization, separate each individual character by space.

Below is the implementation of the above approach :

Java




// 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) + " ");
        }
    }
}


 
 

Output

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:

  1. Define a String.
  2. Use the toCharArray method and store the array of Characters returned in a char array.
  3. Print separated characters using for-each loop.

Below is the implementation of the above approach :

Java




// 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 + " ");
    }
}


Output

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)



Similar Reads

Java Program to Store Even & Odd Elements of an Array into Separate Arrays
Given an array with N numbers and separate those numbers into two arrays by odd numbers or even numbers. The complete operation required O(n) time complexity in the best case. For optimizing the memory uses, the first traverse through an array and calculate the total number of even and odd numbers in it. Create two arrays with size calculated after
2 min read
Implementing our Own Hash Table with Separate Chaining in Java
All data structure has their own special characteristics, for example, a BST is used when quick searching of an element (in log(n)) is required. A heap or a priority queue is used when the minimum or maximum element needs to be fetched in constant time. Similarly, a hash table is used to fetch, add and remove an element in constant time. Anyone mus
10 min read
Java Program to Iterate Over Characters in String
Given string str of length N, the task is to traverse the string and print all the characters of the given string using java. Illustration: Input : str = “GeeksforGeeks” Output : G e e k s f o r G e e k sInput : str = "GfG" Output : G f G Methods: Using for loops(Naive approach)Using iterators (Optimal approach) Method 1: Using for loops The simple
3 min read
Java program to print all duplicate characters in a string
Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = "geeksforgeeks" Output: s : 2 e : 4 g : 2 k : 2 Input: str = "java" Output: a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}.Traverse the string, check if the hashMap already
2 min read
Java Program to Swap Corner Words and Reverse Middle Characters of a String
Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string. Input: "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input: "Hello Bye" Output: "Bye Hello" Methods: Using the concept of ASCII valuesUsing the split() method Method 1: Using the
5 min read
Java Program to Check Whether the String Consists of Special Characters
Special characters are those characters that are neither a letter nor a number. Whitespace is also not considered a special character. Examples of special characters are:- !(exclamation mark), , (comma), #(hash), etc. Methods: Using Character classUsing regular expressionsUsing contains() method Method 1: Using Character class The approach is as fo
5 min read
Java Program to Add Characters to a String
We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows: Illustration: Input: Input custom string = HelloOutput: --&gt; String to be added 'Geeks' --&gt; If end position, Output: HelloGeeks --
5 min read
Java Program to Replace Multiple Characters in a String
In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() methodUsing replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new string resulting from replacing all occurrences of o
3 min read
Java Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
Java Program to Swap characters in a String
The task at hand involves manipulating a string S of length N, given as input. The string is subjected to a series of B swaps, each performed according to the following procedure: The character at position i is swapped with the character located C positions ahead of it, or (i + C)%N. This swapping process is repeated B times, with each iteration st
6 min read
Java Program to Shuffle Characters in a String Without Using Shuffle()
Rearranging the order of characters, in a string can be done by shuffling them. Although the shuffle() method provided by Java's Collections class is handy there are situations where you might require approaches. In this article, we will explore techniques, for shuffling characters in a string without using the shuffle() method. Methods to shuffle
3 min read
Strings formed from given characters without any consecutive repeating characters
Given an array of strings arr[] and a string str, the task is to print all the strings from the array arr which follow the below conditions: The resultant strings shouldn't contain any consecutive repeating characters.The resultant strings should be formed by using only the characters from the string str. Examples: Input: arr[] = { "AABCDA", "ABCDZ
6 min read
Iterate Over the Characters of a String in Java
Given string str of length N, the task is to traverse the string and print all the characters of the given string. Illustration: Input : “GeeksforGeeks” Output : G e e k s f o r G e e k sInput. : “Coder” Output : C o d e r Methods: Using Naive ApproachUsing String.toCharArray() methodUsing CharacterIteratorUsing StringTokenizerUsing String.split()
9 min read
Remove all non-alphabetical characters of a String in Java
Given a string str, consisting of non-alphabetical characters. The task is to remove all those non-alphabetical characters of str and print the words on a new line. Examples: Input: str = "Hello, how are you ?" Output: Hello how are you comma(, ), white space and question mark (?) are removed and there are total 4 words in string s. Each token is p
4 min read
How to remove all non-alphanumeric characters from a string in Java
Given string str, the task is to remove all non-alphanumeric characters from it and print the modified it. Examples: Input: @!Geeks-for'Geeks,123 Output: GeeksforGeeks123 Explanation: at symbol(@), exclamation point(!), dash(-), apostrophes('), and commas(, ) are removed.Input: Geeks_for$ Geeks?{}[] Output: GeeksforGeeks Explanation: underscore(_),
3 min read
Convert List of Characters to String in Java
Given a list of characters. In this article, we will write a Java program to convert the given list to a string. Example of List-to-String ConversionInput : list = {'g', 'e', 'e', 'k', 's'} Output : "geeks" Input : list = {'a', 'b', 'c'} Output : "abc" Strings - Strings in Java are objects that are supported internally by a char array. Since arrays
4 min read
Different Ways to Print First K Characters of the String in Java
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
3 min read
Different Ways to Generate String by using Characters and Numbers in Java
Given a number num and String str, the task is to generate the new String by extracting the character from the string by using the index value of numbers. Examples: Input: str = “GeeksforGeeks” num = 858 Output: GfG Explanation: The 8th, 5th, and 8th position of the characters are extracting from the given string and generate a new string. Input: s
3 min read
Escaping XML Special Characters in Java String
When we read an XML file and try writing to another XML file it is important for us to take care of special characters in the XML. There are some reserved characters in Java that need to be transformed or escaped to be considered as a string literal. If we don't escape these special characters then parsers like DOM or SAX parsers in java would cons
3 min read
Searching For Characters and Substring in a String in Java
Strings are a very important aspect from a programming perspective as many questions can be framed out among strings. There arise wide varied sets of concepts and questions that are pivotal to understanding strings. Now over here will be discussing different ways to play with strings where we will be playing with characters with strings and substri
6 min read
Swapping Characters of a String in Java
As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.In this article we would go through some methods to swap character of a given String and get
3 min read
How to Shuffle Characters in a String in Java?
In this article, we will learn how to shuffle characters in a String by using Java programming. For this, we have taken a String value as input and the method is available in java.util package and this method takes a list as input. Steps to shuffle characters in a String in JavaFirst, take one String value.After that convert this string to the char
2 min read
Extract a Substring Between Two Characters in a String in Java
In Java, the extraction of the substring between the two characters in a string can be implemented with the substring method, and string is a pre-defined method in the class of the String. A String is a pre-defined class of the java.lang package. substring(startIndex, endIndex): This is a pre-defined method of the String class, and it takes the two
2 min read
Swapping Pairs of Characters in a String in Java
Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is. Examples: Input: str = “Java”Output: aJav Explanation: The given string contains even number of characters. Therefore, we swap every pair of characters. Input
3 min read
Convert a String to a List of Characters in Java
Given a String, the task is to convert it into a List of Characters in Java. Examples: Input: String = "Geeks" Output: [G, e, e, k, s] Input: String = "GeeksForGeeks" Output: [G, e, e, k, s, F, o, r, G, e, e, k, s] Naive Method Get the String. Create an empty List of Characters. Add each character of String to the List. Return the List. Below is th
4 min read
Java program to swap first and last characters of words in a sentence
Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example? Examples: Input : geeks for geeks Output :seekg rof seekg Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is. First we will create an Char array of given String by us
2 min read
Java Program to Store Unicode Characters Using Character Literals
ASCII table helps to get computation done earlier but with the ongoing passage of time, there emerge several human-readable languages where the constraint with ASCII was it only supports 256 symbols that too of English only. Now to make computations for other languages there emerges a UNICODE system for computation inside the computer that supports
4 min read
Java Program to Move All Uppercase Characters to the End
Given a string that contains uppercase letters as well as lower case letters. The task is to move all uppercase characters at the end of the String. The uppercase characters must be in the same order as in the original string. Input : "heLLGFg" Output : "hegLLGF" Input : "Hello" Output : "elloH" Here we are having two different approaches to get to
4 min read
Java Program to Illustrate Escaping Characters in Regex
Special Characters like dot(.), hash(#), etc., which have a special meaning to the regular expression need to be escaped to match in the regular expression. For example, if dot(.) is not escaped in a regular expression, it matches any single character, thus giving ambiguous results. Methods: Characters can be escaped in Java Regex in two ways which
3 min read
Java program to count the characters in each word in a given sentence
Write a Java program to count the characters in each word in a given sentence? Examples: Input : geeks for geeksOutput :geeks-&gt;5for-&gt;3geeks-&gt;5 Recommended: Please solve it on PRACTICE first, before moving on to the solution. Approach:Here we have to find out number of words in a sentence and the corresponding character count of each word.
3 min read
Practice Tags :