We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'm trying to code a program to check a string for a certain character and if it's found once (but not less or more than one)in the string i want to print a line to the command box.
How can i achieve this?
Answers
The String class offers lot of ways to do this... From indexOf() to replace()...
Sorry for being a newbie. But that didn't really help me out.
All i want it so see if a string contains a certain character and that this character only occurs once in the string.
String mail = "emailadress@domain.com"; if (mail.contains("@")) { println("Yes the string mail contains ONE '@'"); }
Right now this kind of works. But I want it to println "The string 'mail' contains none or more than one '@' - if @ occurs more than once in the string, or not at all.
What doesn't help you? I give a ready-to-use function (admittedly, not easy to understand), and pointers for other solutions, like indexOf(). Have you looked at this one? It is probably simpler to use.
You can use the version with index (if first result isn't -1, check if there is another occurrence further), or a smart trick would be to compare indexOf() result with the one of lastIndexOf(): if they are different (and different of -1), you have two occurrences.
Made a getCharOccurrences() method relying on String's indexOf(). Hope it works for ya too: O:-)
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#indexOf-int-int-
Another way is use toCharArray() in order to get a
char[]
outta the String passed parameter: =P~https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()
Obvious disadvantage is the extra instantiation of a
char[]
array though. :(However, for huge String objects, the faster array's element comparisons might compensate for it.
Otherwise, for a regular String's length(), this alternative 1 relying on charAt() is possibly faster than any of previous 1s above. Even the indexOf() version. But of course, which 1 is faster wasn't tested yet: b-(
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)
I think it does, any of them...
My own gotOnlyOneChar() version. But using charAt() instead of replaceAll(): (*)
No loop:
@PhiLho, nice indexOf() + lastIndexOf() combo! :-bd Although I'd change parameter
char ch
toint ch
,so it can search for UTF-16 surrogate code points too. *-:) And here's a compact version: :ar!
P.S.: Of course, both indexOf() & lastIndexOf() rely on some
for ()
loop internally! ;)