Counting character in a string

I'm trying to count how many times a characters occurs in a string, and I'm having a lot of trouble. This is what I have so far:
note: the method call has to be public static int countOccs(char f, String s) and I know that it can be done using only loops, for, charAt, and length () and I want to learn it like that.
[I just chose f, s randomly.]
public class Counting {
public static void main(String [ ] args) {
String s = "Testing";
int countOccs = s.length( );
char [ ] charArray = new new char[counting];
for (int i = 0; i < counting; i++) {
charArray[i]
public static int counting(char f, String s) {
I'm really lost. When I try to define char f = "f" or String s = "Testing" in the method call (public static int counting...) I get messages saying that it has already been declared in the call, but there has been nothing assigned to it. Anyways, I feel really lost. I did find a pattern by looking at my notes from awhile ago, but am having trouble filling out parts of it. (Thanks, memory...) I think the problem comes from having to have the method call be public static int counting (char f, String s). That part confuses me a lot because I want it to print out how many characters of f are in a string, but it doesn't have "void" in it so it doesn't return a value.
for (int i=0; i < s.length(); i++)
char f = s.charAt(i);
if (something that looks at the characters)
do something like count
Edited by: MAresJonson on Feb 6, 2009 6:50 PM

h1. The Ubiquitous Newbie Tips
* DON'T SHOUT!!!
* Homework dumps will be flamed mercilessly. [Feelin' lucky, punk? Well, do ya'?|http://www.youtube.com/watch?v=1-0BVT4cqGY]
* Have a quick scan through the [Forum FAQ's|http://wikis.sun.com/display/SunForums/Forums.sun.com+FAQ].
h5. Ask a good question
* Don't forget to actually ask a question. No, The subject line doesn't count.
* Don't even talk to me until you've:
    (a) [googled it|http://www.google.com.au/] and
    (b) had a squizzy at the [Java Cheat Sheet|http://mindprod.com/jgloss/jcheat.html] and
    (c) looked it up in [Sun's Java Tutorials|http://java.sun.com/docs/books/tutorial/] and
    (d) read the relevant section of the [API Docs|http://java.sun.com/javase/6/docs/api/index-files/index-1.html] and maybe even
    (e) referred to the JLS for "advanced" questions.
* [Good questions|http://www.catb.org/~esr/faqs/smart-questions.html#intro] get better Answers. It's a fact. Trust me on this one.
    - Lots of regulars on these forums simply don't read badly written questions. It's just too frustrating.
      - FFS spare us the SMS and L33t speak! Pull your pants up, and get a hair cut!
    - Often you discover your own mistake whilst forming a "Good question".
    - Often you discover you discover you where trying to answer "[the wrong question|http://blog.aisleten.com/2008/11/20/youre-asking-the-wrong-question/]".
    - Many of the regulars on these forums will bend over backwards to help with a "Good question",
      especially to a nuggetty problem, because they're interested in the answer.
* Improve your chances of getting laid tonight by writing an SSCCE
    - For you normal people, That's a: Short Self-Contained Compilable (Correct) Example.
    - Short is sweet: No-one wants to wade through 5000 lines to find your syntax errors!
    - Often you discover your own mistake whilst writing an SSCCE.
    - Often you solve your own problem whilst preparing the SSCCE.
    - Solving your own problem yields a sense of accomplishment, which makes you smarter ;-)
h5. Formatting Matters
* Post your code between a pair of &#123;code} tags
    - That is: &#123;code} ... your code goes here ... &#123;code}
    - This makes your code easier to read by preserving whitespace and highlighting java syntax.
    - Copy&paste your source code directly from your editor. The forum editor basically sucks.
    - The forums tabwidth is 8, as per [the java coding conventions|http://java.sun.com/docs/codeconv/].
      - Indents will go jagged if your tabwidth!=8 and you've mixed tabs and spaces.
      - Indentation is essential to following program code.
      - Long lines (say > 132 chars) should be wrapped.
* Post your error messages between a pair of &#123;code} tags:
    - That is: &#123;code} ... errors here ... &#123;code}
    - OR: &#91;pre]&#123;noformat} ... errors here ... &#123;noformat}&#91;/pre]
    - To make it easier for us to find, Mark the erroneous line(s) in your source-code. For example:
        System.out.println("Your momma!); // <<<< ERROR 1
    - Note that error messages are rendered basically useless if the code has been
      modified AT ALL since the error message was produced.
    - Here's [How to read a stacktrace|http://www.0xcafefeed.com/2004/06/of-thread-dumps-and-stack-traces/].
* The forum editor has a "Preview" pane. Use it.
    - If you're new around here you'll probably find the "Rich Text" view is easier to use.
    - WARNING: Swapping from "Plain Text" view to "Rich Text" scrambles the markup!
    - To see how a posted "special effect" is done, click reply then click the quote button.
If you (the newbie) have covered these bases *you deserve, and can therefore expect, GOOD answers!*
h1. The pledge!
We the New To Java regulars do hereby pledge to refrain from flaming anybody, no matter how gumbyish the question, if the OP has demonstrably tried to cover these bases. The rest are fair game.

Similar Messages

  • How to count number of occurences of a character  in a string

    I want to get the count of occurences of a character within a string. Is there any function for this or should i go for a PLSQL.
    For example is the sting is "occurences" & if i search for character "c", the answer should be 3.
    Regards,
    Sunil.

    SQL> select length('occurence') - length(replace('occurence','c')) from dual;
    LENGTH('OCCURENCE')-LENGTH(REPLACE('OCCURENCE','C'))
    3

  • Count a character within a string

    Give a string, what function can I use to count how many a particular character in the string. For example:
    "abc;def;ghi;xyz"
    I want to find out how many ";" in this string.
    Thank you

    And of course, if the researched character is not in the given string, then you'll return null, to return 0, you'll need a NVL.even if it is in the string you might need a nvl in Vamsi Kasina's solution:
    SQL>  select length (';') - length (replace (';', ';')) cnts
      from dual
          CNTS
    1 row selected.Better:
    SQL>  select nvl(length (';'),0) - nvl(length (replace (';', ';')),0) cnts
      from dual
          CNTS
             1

  • Count the occurance of a character in a string

    What is the function to count the occurance of a character in a string.
    like 'test test1 test2 test3' with in this string there are 3 white spaces.
    instr will give the first one, replace will change the all... and what's for the occurance (number of white spaces, which is 3 in this case) count
    Message was edited by:
    gladnn

    SQL> var a varchar2(25)
    SQL> exec :a := 'gghhhh999jjjj'
    &nbsp
    PL/SQL procedure successfully completed.
    &nbsp
    SQL> select length(:a) - nvl(length(replace(:a,'h','')),0) from dual;
    &nbsp
    LENGTH(:A)-NVL(LENGTH(REPLACE(:A,'H','')),0)
                                               4Rgds.

  • Count the occurence of a character in a string

    Post Author: halfpat
    CA Forum: Formula
    Hello to everyone,
    I use CR 8,0. Is anyone can tell me if this is possible:
    I have a string "12345-C-1 23456-C-2 34567-C-4", how can I count the occurence of the "C" character in this string ?Is the InStr function can help me to do this ?
    I appreciate any suggestion,
    Thanks.

    Post Author: bettername
    CA Forum: Formula
    How about measuring the length of the string, and subtracting the length of the same string where C is replaced with <nothing>?
    len("12345-C-1 23456-C-2 34567-C-4") - len(replace("12345-C-1 23456-C-2 34567-C-4" , "C", ""))

  • Which method to count the number of character in a string?

    Hi all,
    I want to know which class and method to count the number of character in a string?
    Gary

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

  • How to replace a character in a string with blank space.

    Hi,
    How to replace a character in a string with blank space.
    Note:
    I have to change string  CL_DS_1===========CM01 to CL_DS_1               CM01.
    i.e) I have to replace '=' with ' '.
    I have already tried with <b>REPLACE ALL OCCURRENCES OF '=' IN temp_fill_string WITH ' '</b>
    Its not working.

    Hi,
    Try with this..
    call method textedit- >replace_all
      exporting
        case_sensitive_mode = case_sensitive_mode
        replace_string = replace_string
        search_string = search_string
        whole_word_mode = whole_word_mode
      changing
        counter = counter
      exceptions
        error_cntl_call_method = 1
        invalid_parameter = 2.
    <b>Parameters</b>      <b> Description</b>    <b> Possible values</b>
    case_sensitive_mode    Upper-/lowercase       false Do not observe (default value)
                                                                       true  Observe
    replace_string                Text to replace the 
                                         occurrences of
                                         SEARCH_STRING
    search_string                 Text to be replaced
    whole_word_mode          Only replace whole words   false Find whole words and                                                                               
    parts of words (default                                                                               
    value)
                                                                               true  Only find whole words
    counter                         Return value specifying how
                                        many times the search string
                                        was replaced
    Regards,
      Jayaram...

  • Occurence of character in a string

    How can i find how many occurrence of a character in a string?
    Let's say: 010101010101010: there is 8 0 in that string.

    Here's just a different take on the same old problem, tested on 10g ... ;-)
    WITH t AS (SELECT '010101010101010' col1
                 FROM dual
    SELECT SYS_CONNECT_BY_PATH(symbol || ':' || TO_CHAR(no_of_sym), ' ') sym_stat
      FROM (SELECT SUBSTR(t.col1, LEVEL, 1) symbol
                 , COUNT(*)                 no_of_sym
                 , ROW_NUMBER() OVER (ORDER BY SUBSTR(t.col1, LEVEL, 1)) rn
              FROM t
           CONNECT BY LEVEL <= LENGTH(t.col1)
             GROUP BY SUBSTR(t.col1, LEVEL, 1)
    WHERE connect_by_isleaf = 1
    START WITH rn = 1
    CONNECT BY PRIOR rn = rn - 1
    => "0:8 1:7"C.

  • Replacing a special character in a string with another string

    Hi
    I need to replace a special character in a string with another string.
    Say there is a string -  "abc's def's are alphabets"
    and i need to replace all the ' (apostrophe) with &apos& ..which should look like as below
    "abc&apos&s def&apos&s are alphabets" .
    Kindly let me know how this requirement can be met.
    Regards
    Sukumari

    REPLACE
    Syntax Forms
    Pattern-based replacement
    1. REPLACE [{FIRST OCCURRENCE}|{ALL OCCURRENCES} OF]
    pattern
              IN [section_of] dobj WITH new
              [IN {BYTE|CHARACTER} MODE]
              [{RESPECTING|IGNORING} CASE]
              [REPLACEMENT COUNT rcnt]
              { {[REPLACEMENT OFFSET roff]
                 [REPLACEMENT LENGTH rlen]}
              | [RESULTS result_tab|result_wa] }.
    Position-based replacement
    2. REPLACE SECTION [OFFSET off] [LENGTH len] OF dobj WITH new
                      [IN {BYTE|CHARACTER} MODE].
    Effect
    This statement replaces characters or bytes of the variable dobj by characters or bytes of the data object new. Here, position-based and pattern-based replacement are possible.
    When the replacement is executed, an interim result without a length limit is implicitly generated and the interim result is transferred to the data object dobj. If the length of the interim result is longer than the length of dobj, the data is cut off on the right in the case of data objects of fixed length. If the length of the interim result is shorter than the length of dobj, data objects of fixed length are filled to the right with blanks or hexadecimal zeroes. Data objects of variable length are adjusted. If data is cut off to the right when the interim result is assigned, sy-subrc is set to 2.
    In the case of character string processing, the closing spaces are taken into account for data objects dobj of fixed length; they are not taken into account in the case of new.
    System fields
    sy-subrc Meaning
    0 The specified section or subsequence was replaced by the content of new and the result is available in full in dobj.
    2 The specified section or subsequence was replaced in dobj by the contents of new and the result of the replacement was cut off to the right.
    4 The subsequence in sub_string was not found in dobj in the pattern-based search.
    8 The data objects sub_string and new contain double-byte characters that cannot be interpreted.
    Note
    These forms of the statement REPLACE replace the following obsolete form:
    REPLACE sub_string WITH
    Syntax
    REPLACE sub_string WITH new INTO dobj
            [IN {BYTE|CHARACTER} MODE]
            [LENGTH len].
    Extras:
    1. ... IN {BYTE|CHARACTER} MODE
    2. ... LENGTH len
    Effect
    This statement searches through a byte string or character string dobj for the subsequence specified in sub_string and replaces the first byte or character string in dobj that matches sub_string with the contents of the data object new.
    The memory areas of sub_string and new must not overlap, otherwise the result is undefined. If sub_string is an empty string, the point before the first character or byte of the search area is found and the content of new is inserted before the first character.
    During character string processing, the closing blank is considered for data objects dobj, sub_string and new of type c, d, n or t.
    System Fields
    sy-subrc Meaning
    0 The subsequence in sub_string was replaced in the target field dobj with the content of new.
    4 The subsequence in sub_string could not be replaced in the target field dobj with the contents of new.
    Note
    This variant of the statement REPLACE will be replaced, beginning with Release 6.10, with a new variant.
    Addition 1
    ... IN {BYTE|CHARACTER} MODE
    Effect
    The optional addition IN {BYTE|CHARACTER} MODE determines whether byte or character string processing will be executed. If the addition is not specified, character string processing is executed. Depending on the processing type, the data objects sub_string, new, and dobj must be byte or character type.
    Addition 2
    ... LENGTH len
    Effect
    If the addition LENGTH is not specified, all the data objects involved are evaluated in their entire length. If the addition LENGTH is specified, only the first len bytes or characters of sub_string are used for the search. For len, a data object of the type i is expected.
    If the length of the interim result is longer than the length of dobj, data objects of fixed length will be cut off to the right. If the length of the interim result is shorter than the length of dobj, data objects of fixed length are filled to the right with blanks or with hexadecimal 0. Data objects of variable length are adapted.
    Example
    After the replacements, text1 contains the complete content "I should know that you know", while text2 has the cut-off content "I should know that".
    DATA:   text1      TYPE string       VALUE 'I know you know',
            text2(18)  TYPE c LENGTH 18  VALUE 'I know you know',
            sub_string TYPE string       VALUE 'know',
            new        TYPE string       VALUE 'should know that'.
    REPLACE sub_string WITH new INTO text1.
    REPLACE sub_string WITH new INTO text2.

  • Alternative to find unique records with 60 character in selection string.

    Hi,
    We have to find out the values from the Infoobject. When we try to display data from an master object, the maximum length of selection it accepts 45 characters only but we need to input data around 60 characters in selection.
    Thing we tried:
    1. Selecting complete data without any condition but it did not work due to large volume of data.
    2. We tried to extract data from RSA3 but it did not work due to large volume of data.
    Please suggest me alternative to find unique records with 60 character in selection string.
    Regards,
    Himanshu Panchal.

    This sounds a bit strange. Are you perhaps mistakenly storing text data incorrectly as the primary key of the master data? I can't think of any actual data that is that length to ensure usinqueness - even GUIDs are maximum 32 characters - but GUIDs don't count as actual "readable" data although you do need to be able to select it from time to time. Perhaps you have a super secure password hash or something like it ?
    Also are you expecting to have a unique single record returned by your selection? To do this would in general REQUIRE that ALL the data is read because master data is not stored in the DB sorted by the data itself, but stored instead sorted by the it's SID.
    When you say you are selecting data from master data, which master data tables are you using? I have been able to select data from very large MD table (15 million unique records) using SE16 with no problems. Just enter the table name, and before you execute just count the number of records - it helps to know what you want to end up with.
    Have you tried using wild cards (the *) to preselect a smaller number of records : * a bit of your 60 character string *
    If you are trying to select from a non-key field you will encounter performance issues, but you can still use the wildcards, and get a result.
    Don't use RSA3 it was designed to make selections and group them into datapackets. It's not the same as selecting directly on the table in SE11 or SE16

  • Need to count character from an xml

    Hi all,
    I need to count character from a field. and store it in a variable. My datasource is from xml file.
    Any ideas for the syntax?
    thanks in advance,
    Paolyn

    Use <?string-length(FIELD)?> to get the count of characters.

  • Finding the occurences of | character in a string

    Hi There,
    I want to restrict the occurrences of | character in a string to some number. How can I make this check using regular expressions.
    Thanks,
    --JJ                                                                                                                                                                                                                                                                                                                               

    sabre150 wrote:
    guitar_man_F wrote:
    sabre150 wrote:
    jose wrote:
    So can you please suggest me a sample regex which will do this.
    --JJErr.. err.. err.. reply #2?Not quite. I believe he said restrict it to a certain max number of |, not remove all instances. I think.
    Look again. I remove anything that is NOT a '|' char and then count what is left.Oops! My bad! You're right. That would work.
    - Adam

  • Strip the first character from a string

    i am trying to strip the leftmost character from a string
    using the following:
    <cfset Charges.DTL_CHG_AMT_EDIT =
    #Right(Charges.DTL_CHG_AMT_EDIT,Len(Charges.DTL_CHG_AMT_EDIT)-1)#>
    i keep getting the following error:
    Parameter 2 of function Right which is now -1 must be a
    positive integer

    > RemoveChars() much easier than Right()? How so?
    Semantically, if the object of the exercise is to *REMOVE
    CHARacters from a
    string* (which it is, in this case), it is simply better
    coding to use
    removeChars() rather than right(). That, and it's one less
    function call
    (the RIGHT() solution also requires a call to LEN() for it to
    work).
    So removeChars() is "easier" because it reflects the intent
    of the exercise
    directly, is simpler logic, is easier to read, and - I can't
    be arsed
    counting keystrokes - is probably less typing.
    That'd be how.
    Adam

  • How to get each character in a string

    as in 'C' we use arrays to get each character of a string stored in array.how can we get each character of a string stored in a variable.

    Hi,
    For that you need to do offset.
    for example one variable called VAR contains string 'HUMERAH'.
    if you want each character of that string then you need to decalre as many variable as the number of string.
    like
    data : var1(1),
             var2(1),
    var(3),
    var(4).
    var1 = var+(1).
    var2 = var+1(1).
    var3 = var+2(1).
    var4 = var+3(1).
    now var1,var2,var3,var4. contains the single characters.
    Regards,
    Guru
    mark helpful answers

  • Replacing a character in a string to another character

    hi,
    i need to write a function or procedure to replace the character of a string value suppose:
    l_error:= 'abcdefghijklmnop' is a string
    i need write a function or procedure to replace the character "c" to "z"
    that data in l_error is not in any table.
    thanks,
    AJ

    I want to Replace all the Existence of the word - "Test" in a string with "Test1" whereever a space exits before the word Test and someother alphabet after "Test" i.e. Test will be replaced with Test1 if a word starts with Test and contains more alphabets also. For example - TestName should be replaced with Test1Name while MyTest should not be updated to MyTest1.
    I have tried to use below query which uses oracle regular expressions -
    SELECT REGEXP_REPLACE('MYCOMPANY TEST TESTGEET INDIA PVT LTD TEST','\s(TEST)\w',' TEST1') FROM DUAL
    Output -
    "MYCOMPANY TEST *TEST1EET* INDIA PVT LTD TEST"
    Here, it has also replaced the G also from TESTGEET and resulted in TEST1EET while i want TEST1GEET.
    Can someone please suggest how can i do this..... may b m doing some silly mistake but sorry m a newbie to regular expression...
    Thanks in advance..

Maybe you are looking for

  • Out of the box execution plan for Payables EBS 11.5.10

    Has anyone else experienced performance issues with the out of the box execution plan for the Payables subject area for Oracle EBS 11.5.10? Our incremental ETL for this particular subject area is taking 8+ hours. I understand that there are several f

  • How to program a 50 point look-up table in LabVIEW7 Express

    I'm trying to write a VI to measure an analog input, compare the input values to the values in a preprogrammed 50 point lookup table, and produce the corresponding output value from the lookup table. Is there a "canned" VI I can use?

  • How do i store and fetch image from the Database(Access)

    i am facing one problem in inserting the image into the database.the steps i followed as 1)i have created one database(access) as "Image" and into that one table as "Image" and field as "image" type of the field is ole object. 2)i have inserted one i

  • Re: MBean calling ejb class loading issue

    Must think before typing.. If I have the ejb register a listener on the mbean and have the mbean emit an event the detyped notification from the mbean will break the link between the mbean class loader and the ejb loader. I think ;-) Ill try it. Pete

  • Application setup

    Hii there, I've built a desktop application, and now I'm going to build setup for that application. I'm having the .jar file for the same. could you else please tell me what is the best way to do it! thanks... Dev