String Methods Part 2
Part of the Fundamentals section of Coddy's Java journey — lesson 68 of 73.
String splitting allows you to break a string into an array, while joining lets you combine array items into a string.
The .split() method divides a string into an array of substrings based on a delimiter.
Split by whitespace:
String text = "apple banana cherry";
String[] fruits = text.split(" ");
System.out.println(Arrays.toString(fruits));
// ["apple", "banana", "cherry"]Split with specific delimiter:
String data = "john,25,new york";
String[] dataArr = data.split(",");
System.out.println(Arrays.toString(dataArr));
// ["john", "25", "new york"]The String.join() method combines elements of an iterable into a single string.
Basic joining:
String[] words = {"Hello", "World", "Java"};
String text = String.join(" ", words);
System.out.println(text);
// "Hello World Java"Join with different separator:
String[] fruits = {"apple", "banana", "cherry"};
String line = String.join(",", fruits);
System.out.println(line);
// "apple,banana,cherry"Challenge
EasyWrite a program that takes two inputs: a text string and a delimiter character. The program should replace all single spaces (" ") in the text with the specified delimiter and print the modified string.
Cheat sheet
The .split() method divides a string into an array based on a delimiter:
String text = "apple banana cherry";
String[] fruits = text.split(" ");
// ["apple", "banana", "cherry"]
String data = "john,25,new york";
String[] dataArr = data.split(",");
// ["john", "25", "new york"]The String.join() method combines array elements into a single string:
String[] words = {"Hello", "World", "Java"};
String text = String.join(" ", words);
// "Hello World Java"
String[] fruits = {"apple", "banana", "cherry"};
String line = String.join(",", fruits);
// "apple,banana,cherry"Try it yourself
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
String delimiter = scanner.nextLine();
// Write your code below
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else