Java: Splitting a String at a certain character
If you want to split a string at a certain character in a string to several new strings, this is a way to do it.
public static void main(String[] args) {
String input = "BytePhil|*|PhilsPW!";
int iend = input.indexOf("|*|");
int length = input.length();
String username = null;
String password = null;
if (iend != -1) {
username = input.substring(0, iend);
password = input.substring(iend + 3, length);
}
System.out.println("Username: " + username + ", PW: " + password);
// Output: "Username: BytePhil, PW: PhilsPW!"
}
If you want to add more parameters to your input string like an email you can do this by adding a new int with the indexOf another splitting character and also adding a new string that’s defined by substring starting at your new character +3 (because in this case „|*|“ are 3 characters) and ending at the end of the input string. In practise this could look something like this:
public static void main(String[] args) {
String input = "BytePhil|*|PhilsPW!|'|[email protected]";
int iend = input.indexOf("|*|");
int iend1 = input.indexOf("|'|");
int length = input.length();
String username = null;
String password = null;
String email = null;
if (iend != -1) {
username = input.substring(0, iend);
password = input.substring(iend + 3, iend1);
email = input.substring(iend1 + 3, length);
}
System.out.println("Username: " + username + ", PW: " + password + ", Email: " + email);
// Output: "Username: BytePhil, PW: PhilsPW!, Email: [email protected]"
}