5 Replies Latest reply: Dec 17, 2008 9:52 PM by 843785 RSS

    Detecting the first char inside string

    843785
      Hi,

      I search through all the String and char method but it doesn't seems to be any method to do this.

      Is there anyway I can detect the first char in a String
      Eg:
      @#@Hello!!

      Is there a method that allows me to detect H directly?
        • 1. Re: Detecting the first char inside string
          843785
          String s = "@#@Hello!!";
          int positionOfH = s.indexOf("H")
          • 2. Re: Detecting the first char inside string
            843785
            blazingwolf7 wrote:
            Hi,

            I search through all the String and char method but it doesn't seems to be any method to do this.

            Is there anyway I can detect the first char in a String
            Eg:
            @#@Hello!!

            Is there a method that allows me to detect H directly?
            There isn't a built in function like String.firstChar() that would give you the first character of any String. You can easily make one though.
            • 3. Re: Detecting the first char inside string
              843785
              Ermm...sorry I didn't make myself clearer, but I need a more flexible method. Because the String pass in may varies from time to time
              • 4. Re: Detecting the first char inside string
                843785
                blazingwolf7 wrote:
                Ermm...sorry I didn't make myself clearer, but I need a more flexible method. Because the String pass in may varies from time to time
                You'll need to build one yourself.
                • 5. Re: Detecting the first char inside string
                  843785
                  I guess you mean the first character of a particular type - excluding '@' and '#'.
                  morgalr wrote:
                  There isn't a built in function like String.firstChar() that would give you the first character of any String. You can easily make one though.
                  There is [String.charAt(int index)|http://java.sun.com/javase/6/docs/api/java/lang/String.html#charAt(int)] which returns the character at position index. This method can't read your mind though, so charAt(0) will return the very first character regardless of whether it is "good".

                  In the Character class there is also a static method [isLetter(character)|http://java.sun.com/javase/6/docs/api/java/lang/Character.html#isLetter(int)] which reports "true" if the supplied character is a letter. There are lots of other methods in this class to report on the type of letter.

                  Perhaps you could put these ideas together: write a loop to inspect each letter in turn until you come to one that is "good".