In this article, we are going to see how to split a string manually without using any in-built function. To split a string, we need an input string and a delimiter. A delimiter is a character on which the string needs to be split.
Example :
Input :
String: W3Colleges is a wonderful portal.
Delimiter: ” ” (Space)
Output :
W3Colleges
is
a
wonderful
portal.
Approach :
- The characters of the string have to be read one by one and kept appending in a temporary string until a delimiter is read.
- When the delimiter is read, print the temporary string. Re-initialize the temporary string to empty string.
- There is one more case to be handled which is if the character read is the last character, but it is not the delimiter.
- Like in the previous example where the delimiter was a space (” “), the end of the sentence contained a “.” which was not the delimiter.
- Since it was the last character of the string, the temporary string needs to be printed as it as.
Implementation :
class Main {
public static void printWords(String text, char delimiter)
{
// Temporary string
String word = "";
for (int i = 0; i < text.length(); i++) {
// Read the current character
char ch = text.charAt(i);
// If the character is delimiter, print the word
if (ch == delimiter) {
System.out.println(word);
word = "";
}
// If its the end of string, print the word
else if (i == text.length() - 1 && ch != delimiter) {
word += ch;
System.out.println(word);
}
// Add characters to word
else {
word += ch;
}
}
}
public static void main(String[] args) throws java.lang.Exception
{
printWords("W3Colleges is a wonderful portal.", ' ');
}
}