Identify a character in a string .............

An exercise of a text book of java.
Count the number of letter 'a' appearing in a word. I can't do that. Here is my program, please help.
import kenya.io.InputReader;
import java.util.StringTokenizer;
public class e47{
public static void main ( String [] args ){
     System.out.println("Please type in a word ---->");
     String a = InputReader.readString();
     int r = countA(a);
     if (/*countA(a) == 0*/r == 0 ){
     System.out.println("There's no letter 'A' in this word.");
     else{
     System.out.println("The letter 'A' appears " + countA(a) + " times.");
static int countA(String a){
          StringTokenizer letterA = new StringTokenizer (a);
          int acc = 0;
          while (letterA.hasMoreTokens()){
               if ( letterA.nextToken() == "a"){
               acc = acc + 1;
          return acc;
Thanks a lot!!

StringTokenizer parses "words" separated by a "token" such as a space, newline, tab, whatever. That's why it's not working for your purpose.
Instead, try something like:
int count = 0;
for (int i = 0; i < a.length(); i++)
  if (a.charAt[i] == 'a')
    count++;
return count;

Similar Messages

  • NewLine Character in the String received from Interactive Adobe Form

    Hello Experts,
    Following is the issue we have with interactive Adobe Form
    We have a text area within the form. User enters the text in multiple lines in this text area.
    We are calling a backend function module designed in SE37 that accepts and process the data from the adobe form.  We are also processing the string data user enters in the text area.
    When we receive the string from the form, the newline character within the string is displayed as '#' in the debugger. We tried splitting this string using cl_abap_char_utilities=>newline and cl_abap_char_utilities=>cr_lf  but NO luck. Though in the debugger we see cl_abap_char_utilities=>newline  as '#'  in the debugger and also '#' is present within the string, for some reason when string is processed to find cl_abap_char_utilities=>newline, we can find/locate it.
    Because ABAP code is not able to identify the newline character within the string received from Adobe form, we are not able to maintain the formatting of the string as it was entered in the form.
    Any help to resolve this issue is appreciated.
    Thanks in Advance.
    Regards,
    Bhushan

    Hi Bhushan,
    I was going through your issue, and I feel this is something you can do with scripting. Basically you should read whole string and find the new line character and replace with a space or comma, as per your requirment.
    Do like following:
    In the exit event of the field select java script and write following code:
    var strng = this.rawValue;
    strng.replace(/\n/g, " ");
    above im reaplcing new line with a space.
    I think it should work I have not tested it. Pls update if you test it .
    Regards,
    Ravi.D

  • 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

  • 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..

  • Function in oracle to find number of occurances of a character in a string

    hi,
    is there any function in oracle to find the number of ocurrances of a character in a string ?
    or is there any simple way of doing the same, rather than writting many lines of code as my program is already very complex.
    Maria

    Hi Maria,
    I don't know of such a function in Oracle, but maybe you could use this:
    length(search_string) - length(replace(search_string, character_to_be_found))
    For example: select length('Hello') - length ( replace('Hello', 'l')) from dual;
    Hope this is what you're looking for
    Danny

  • How to escape the character in a string?

    I have the following code that is causing an error. I'm
    attempting to use < (less than) character in a string that is
    part of a dynamic query:
    <cfif url.age eq 1>
    <cfset askAge = " < 15">
    <cfelseif url.age eq 10>
    <cfset askAge = " Between 56 and 60">
    <cfelseif url.age eq 11>
    <cfset askAge = " > 60">
    </cfif>
    The error occurs as a result of the line <cfset askAge = "
    < 15">. The > 60 works fine. What I need is to build the
    SQL statement SELECT * FROM myTable WHERE age < 15
    ColdFusion sets the string properly but when I try to run the
    query I guess it thinks I'm trying to open a tag. The exact error
    is:
    The content beginning "< " is not legal markup. Perhaps
    the " " (&#20;) character should be a letter.
    The content beginning "< " is not legal markup. Perhaps
    the " " () character should be a letter.
    I can't use the ASCII code for this character as the database
    will obviously crap out.
    Any help would be greatly appreciated and many thanks in
    advance.
    Dave

    Dave,
    What if you passed off the output of the lt/gt symbols to the
    query itself?
    Something like,
    <cfif url.age eq 1>
    <cfset compareOperator = "less"/>
    <cfset askAge = "15">
    <cfelseif url.age eq 10>
    <cfset compareOperator = "between"/>
    <cfset askAge = " 56 and 60">
    <cfelseif url.age eq 11>
    <cfset compareOperator = "greater"/>
    <cfset askAge = "60">
    </cfif>
    Then in the query:
    <cfquery name="qTest" datasource="dsn">
    SELECT * FROM myTable
    WHERE age
    <cfswitch expression="#compareOperator#">
    <cfcase value="less">
    <
    </cfcase>
    <cfcase value="greater">
    >
    </cfcase>
    <cfcase value="between">
    BETWEEN
    </cfcase>
    <cfdefaultcase>
    =
    </cfdefaultcase>
    </cfswitch>
    #askAge#
    </cfquery>
    Probably a better way, at least a more efficient way, but
    just a thought...cfswitch processed pretty quickly and this would
    remove any issues with trying to use <> symbols.
    Cheers,
    Craig

  • Sample code to identify special characters in a string

    Hi,
    I need to identify special characters in a string.... could anybody send me some code please.......
    Thanks,
    Best regards,
    Karen

    data: str(100) type c.
    data: str_n type string.
    data: str_c type string.
    data: len type i.
    data: ofst type i.
    str = '#ABCD%'.
    len = strlen( str ).
    do.
      if ofst = len.
        exit.
      endif.
      if str+ofst(1) co sy-abcde.
        concatenate str_c str+ofst(1) into str_c.
      else.
        concatenate str_n str+ofst(1) into str_n.
      endif.
      ofst = ofst + 1.
    enddo.
    write:/ str.
    write:/ str_c.
    write:/ 'spacial chracter',20 str_n.
    Function module  <b>SF_SPECIALCHAR_DELETE</b> <b>DX_SEARCH_STRING</b>
    l_address1 = i_adrc-street.
    CHECK NOT L_ADDRESS1 IS INITIAL.
    len = STRLEN( l_address1 ).
    do len times.
    if not l_address1+l(1) ca
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '.
    if i_adrc-street+l(1) CO sy-abcde.
    elseif i_adrc-street+l(1) CO L_NUMCHAR.
    exit.
    endif.
    l = l + 1.
    enddo.
    data : spchar(40) type c value '~!@#$$%^&()?...'etc.
    data :gv_char .
    data:inp(20) type c.
    take the string length .
    len = strlen (i/p).
    do len times
    MOVE FNAME+T(1) TO GV_CHAR.
    IF gv_char CA spchar.
    MOVE fnameT(1) TO inp2T(1).
    ENDIF.
    T = T + 1.
    enddo.
    REPORT ZEX4 .
    PARAMETERS: fname LIKE rlgrap-filename .
    DATA: len TYPE i,
    T TYPE I VALUE 0,
    inp(20) TYPE C,
    inp1(20) type c,
    inp2(20) type c,
    inp3(20) type c.
    DATA :gv_char.
    data : spchar(20) type c value '#$%^&*()_+`~'.
    START-OF-SELECTION.
    CONDENSE fname.
    len = strlen( fname ).
    WRITE:/ len.
    DO len TIMES.
    MOVE FNAME+T(1) TO GV_CHAR.
    IF gv_char ca spchar.
    MOVE fnameT(1) TO inpT(1).
    ENDIF.
    T = T + 1.
    ENDDO.
    CONDENSE INP.
    write:/ 'Special Characters :', inp.
    Rewards if useful..........
    Minal

  • How to get a set of character within a string?

    Hi,
    I need to cut a set of character within a string. I have tried everthing but I need help.
    Example.
    Database Version 11.2.0.3
    create table tst_string (message varchar2(600));
    insert into tst_string values ('ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)');
    insert into  tst_string values ('ANE4175I Starting Full VM restore of VMware Virtual Machine ''mfujiwara'' target node name=''VC1_DC1'', data mover node name=''VC1_DC1_DM3''  (SESSION: 3780)');
    commit;
    select * from tst_string;
    MESSAGE
    ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)
    ANE4175I Starting Full VM restore of VMware Virtual Machine 'mfujiwara' target node name='VC1_DC1', data mover node name='VC1_DC1_DM3'  (SESSION: 3780)
    ## I want get
    # From first line following values:
    node OSOGBO
    filespace OSOGBO\SystemState
    examined 43
    deleted 43
    retrying 0
    failed 0
    # From second line
    mfujiwara
    VC1_DC1
    VC1_DC1_DM3Any help can be useful...
    Thanks in advance.

    Hi Frank,
    It looks like message can be seen as delimited lsit of sub-messages, where a number of different characters (perhaps ',' amd ':') may serve as delimiters. Each sub-message may or consist (entirely or in part) of something you want to display.Yes. In my first case where is "ANR0166I" I want get the characteres before "," (e.g "OSOGBO," I want get "OSOGBO") excluding "(SESSION: 1506, PROCESS: 2)"
    Would a user-define PL/SQL function be okay for you?Yes.. no problem.
    I'm not good with shell script, but will try show what I want using SHELL commands:
    See this example:
    ### I create a file named "tst_string"
    $ vi tst_string
    ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState\NULL\System State\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)
    ## So I used a function sed to get my desired values. The command bellow is poor, but My point is the result.
    $ cat tst_string | sed 's/ANR0166I.*node //g' | sed 's/, filespace//g' | sed 's/, copygroup BACKUP and object type GROUP BASE with processing statistics: //g' | sed 's/. (SESSION.*//g' | sed 's/, deleted//g' | sed 's/, retrying//g' | sed 's/, and failed//g'
    OSOGBO OSOGBO\SystemState\NULL\System State\SystemState 43 43 0 0The result was:
    NODE     FILESPACE                              Examined     Deleted     Retrying        Failed      
    OSOGBO      OSOGBO\SystemState\NULL\System State\SystemState     43           43      0           0I will go check the links wich you mentioned.
    Thanks

  • 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...

  • How to check the occurrence of a character in a string

    Hello Experts,
    I have a scenario where in I have to check the occurrence of a character in a string and based on that I have to pass a data into target field.
    I was wondering whether this can achieved with mapping functions or Do I have to use an UDF.
    Thanks in advance.
    Regards
    Advit Ramesh

    Hi Advit,
    You can achieve this by using standard function indexOf from the text category. Pass in the input string and the character value you want to check for as the input.
    Standard Functions (SAP Library - SAP Exchange Infrastructure)
    If the output is -1, then the character is not in the string, otherwise it is.
    Rgds
    Eng Swee

  • The first character in a string

    I need to return the first character of a string, convert it to an integer, and compare it with another integer to see if they're the same. Sounds simple, even for me, but it won't work!!!
    // First question >
    Object userValue1 = JOptionPane.showInputDialog("Blah Blah Blah", JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
    Variables.placeholder = (int) userValue1.charAt(0);This is the error I get
    C:\Documents and Settings\imholt\My Documents\OOPAttempt\21_Questions\Engine.java:170: cannot resolve symbol
    symbol : method charAt (int)
    location: class java.lang.Object
              Variables.placeholder = (int) userValue1.charAt(0);
    ^
    1 error
    I have a sneaky suspicion that once I find out what the problem was, I will ask myself why I didn't see it before...

    Try this
    Object userValue1 = JOptionPane.showInputDialog("Blah Blah Blah", JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
    String str = userValue1.toString();
    Variables.placeholder = (int) str.charAt(0);

  • Find a character in a string

    How will you locate a specific character inside a string?
    Thanks in advance!!!

    > The best place to start with this type of question is
    the documentation. Take a look at string functions:
    >
    http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions-pt0_18.html
    Absolutely.
    Even if one types in "coldfusion find in string" in Google,
    the first
    result is on the money (for CFMX7, not CF8, but still).
    Adam

  • Truncating last character in a string

    I am making a dialpad. It is just for display so I am using a
    string for the numbers selected. I am trying to make a back button
    that would clear the last number added. I tried mystring.length-1
    but that doesn't seem to be doing the trick. Is there a simple way
    to truncate the last character in a string, of variable
    length??

    Here's an example
    var someStr="asdfasdf saf asdf sadfas dfs fsa asf";
    while (someStr.length) {
    someStr = someStr.substring(0,someStr.length-1)
    trace(someStr);
    }

  • Having the '\' character in a string

    I get errors when I try to construct a string, say like this:
    String blahblah = new String("IBM\ROOT\IMAGE");
    Basically it seems like I can't store that '\' character in a string at all. Is this true?
    Thanks in advance.

    the '\' character is used to indicate an escape sequence, used for things like '\n' (new line). To do what you want you can do this:
    String blahblah = new String("IBM\\ROOT\\IMAGE"); //notice the double slash '\\' you would also have to do this for double and single quotes, e.g. ( new String("Bill said, \" Anne told me to \'go home now\'\"") : for... Bill said, "Anne told me to 'go home now'")

Maybe you are looking for

  • Conc managers not coming up

    Hi, I have a funny situation here. I am running 11i on windows server 2003. When i start the conc. managers the application hangs.( I mean i can not open the forms). And when i stop the conc. manager the hanged forms open immediately. This is on the

  • Disk Utility frozen?

    Hey all Got a WD My Book and plugged it into my iMac 3.06. Not realizing that it was FAT formatted, I started moving stuff onto it... then realizing the 4GB file size limit that the Windows format has, I backed up my data and ran disk utility to refo

  • Does this system even have a search function? Also, is there a way to not show account name?

    Ugh, I just downloaded this yesterday, so I'm only really starting to try it out today and wow, did they want to copy off of microsoft or something with the search function? First they get rid of "by file name" for the search, and then search itself

  • Where is "Shadow" in the Overlays panel?

    In the Slideshow module the "Overlays" panel is supposed to have a "Shadow" section (according to the User Manual and the Help file). However, all I can see in the "Overlays" panel is the following three sections: "Identity Plate", "Rating Stars" and

  • Can't send videos via text message or email.  Why is this??

    It keeps telling me "Sorry, you cannot add this video to your message."   The videos I've attempted to send are only 3 seconds to 19 seconds.  Can't send via email either because they're "too large?"