'Tell if a certain delimeter is in a string

I tried setting a Scanner's delimiter to "\t" (and using the Scanner.hasNext() method) to tell if there was a tab in a String, but it returns true regardless of whether or not the delimiter is in the string. I also tried splitting the string with "\t", but this did not error out, even when there was no tab character. How can you tell if there is a tab?



Solution 1:[1]

The Scanner delimiter will effectively remove that from the string; it finds text before and after that delimeter, whether it exists or not.

Similarly, splitting doesn't care if the split pattern exists. However, you could check the size of the list. For example, "foobar".split("-").length is 1, but "foo-bar".split("-").length is 2, indicating the hyphen exists (check boolean exists = string.split(pattern).length > 1).

The better solution for a tab would just be string.contains("\t")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OneCricketeer