Reputation: 35
I managed to split a given word or sentence by a certain symbol, now I'm wondering if I can do this with multiple symbols as a string. For example if I had ("1+1=2"), and try to split it by("+=")?
I thought about declaring symbol as a String and then put the loop that I already have in another one so that ever character in word would be tested for every character in symbol, but to be honest it confuses me.
^-^ I'm thankful for any advice.
public static void splitBySymbol() {
int i = 0;
while (i < word.length()) {
if (word.charAt(i) == symbol) {
System.out.println( word.substring(0,i)); ;
word = word.substring(i + 1);
i = -1;
}
i++;
}
}
Upvotes: 0
Views: 74
Reputation: 13533
If you just want to print the parts, you can:
public static void splitBySymbol(String word, String symbols)
{
// Check each char
for (int i = 0; i < word.length(); i++) {
// Get the current char and convert to string (for contains())
String c = Character.toString(word.charAt(i));
// If it is a delimeter, print a new line
if (symbols.contains(c)) {
System.out.println();
}
// Otherwise, print the char
else {
System.out.print(c);
}
}
}
Upvotes: 1