println if a string contains a certain character only once

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()...

  • edited November 2014
    String toCheck = "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.";
    
    void draw()
    {
    }
    
    void keyPressed()
    {
      if (key == CODED)
        return;
      if (check(key, toCheck))
      {
        background(#00FF00);
      }
      else
      {
        background(#FF0000);
      }
    }
    
    boolean check(char c, String toCheck)
    {
      String remaining = toCheck.replaceAll("[^" + c + "]", "");
      println(c + " >" + remaining + "<");
      return remaining.length() == 1;
    }
    
  • 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.

  • edited November 2014

    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-

    /**
     * GetCharOccurrences (v1.02)
     * by GoToLoop (2014/Nov/11)
     *
     * forum.processing.org/two/discussion/8066/
     * println-if-a-string-contains-a-certain-character-only-once
     */
    
    void setup() {
      println(getCharOccurrences("emailadress@domain.com", '@'));
      println(getCharOccurrences("emailadress domain.com", '@'));
      println(getCharOccurrences("email@adress@domain@com", '@'));
      println(getCharOccurrences("@emailadressdomain.com@", '@'));
    
      exit();
    }
    
    static final int getCharOccurrences(String s, int ch) {
      int count = 0, idx = -1;
      while ( (idx = s.indexOf(ch, idx+1)) != -1 )  ++count;
      return count;
    }
    
  • edited November 2014

    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()

    static final int getCharOccurrences(String s, char ch) {
      int count = 0;
      for (char c : s.toCharArray())  if (c == ch)  ++count;
      return count;
    }
    

    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)

    static final int getCharOccurrencesAlt(CharSequence s, char ch) {
      int count = 0, idx = s.length();
      while (idx-- != 0)  if (s.charAt(idx) == ch)  ++count;
      return count;
    }
    
  • Sorry for being a newbie. But that didn't really help me out.

    I think it does, any of them...

    String mail = "emailadress@domain.com";
    String wrongMail = "emailadress@@domain.com";
    
    void setup() {
    
      if (containsOnlyOne('@', mail)) {
        println("Yes the string contains only ONE \'@\'");
      }
    
      if (containsOnlyOne('@', wrongMail)) {
        println("Yes the string contains only ONE \'@\'");
      } else {
        println("this one does not contains only one \'@\'");
      }
    }
    
    // PhiLho's function...
    boolean containsOnlyOne(char c, String toCheck)
    {
      String remaining = toCheck.replaceAll("[^" + c + "]", "");
      return remaining.length() == 1;
    }
    
  • edited November 2014

    My own gotOnlyOneChar() version. But using charAt() instead of replaceAll(): (*)

    // forum.processing.org/two/discussion/8066/
    // println-if-a-string-contains-a-certain-character-only-once
    
    void setup() {
      println(gotOnlyOneChar("emailadress@domain.com", '@'));
      println(gotOnlyOneChar("emailadress domain.com", '@'));
      println(gotOnlyOneChar("email@adress@domain@com", '@'));
      println(gotOnlyOneChar("@emailadressdomain.com@", '@'));
    
      exit();
    }
    
    static final boolean gotOnlyOneChar(CharSequence s, char ch) {
      boolean foundOneOnly = false;
      int idx = s.length();
    
      while (idx-- != 0)  if (s.charAt(idx) == ch)
        if ( !(foundOneOnly ^= true) )  return false;
    
      return foundOneOnly;
    }
    
  • No loop:

    void setup() 
    {
      println(hasOnlyOneCharOccurence("emailadress@domain.com", '@'));
      println(hasOnlyOneCharOccurence("emailadress domain.com", '@'));
      println(hasOnlyOneCharOccurence("email@adress@domain@com", '@'));
      println(hasOnlyOneCharOccurence("@emailadressdomain.com@", '@'));
    
      exit();
    }
    
    boolean hasOnlyOneCharOccurence(String s, char ch) 
    {
      int p1 = s.indexOf(ch);
      if (p1 < 0)
        return false;
      int p2 = s.lastIndexOf(ch);
      return p2 == p1;
    }
    
  • edited November 2014

    @PhiLho, nice indexOf() + lastIndexOf() combo! :-bd Although I'd change parameter char ch to int ch,
    so it can search for UTF-16 surrogate code points too. *-:) And here's a compact version: :ar!

    // forum.processing.org/two/discussion/8066/
    // println-if-a-string-contains-a-certain-character-only-once
    
    void setup() {
      println(hasOnlyOneCharOccurrence("emailadress@domain.com", '@'));
      println(hasOnlyOneCharOccurrence("emailadress domain.com", '@'));
      println(hasOnlyOneCharOccurrence("email@adress@domain@com", '@'));
      println(hasOnlyOneCharOccurrence("@emailadressdomain.com@", '@'));
    
      exit();
    }
    
    static final boolean hasOnlyOneCharOccurrence(String s, int ch) {
      int idx = s.indexOf(ch);
      return idx == -1? false : s.lastIndexOf(ch) == idx;
    }
    

    P.S.: Of course, both indexOf() & lastIndexOf() rely on some for () loop internally! ;)

Sign In or Register to comment.