Check for a character in a string

Hi you all.
I wanted to know how to check if a character is in a String.
I'll explain. I have a String "HELLO" and now I would like to know if this String contains an '&'. How to handle that?
Greetz,
Frenck

Hi Frenck,
Try the following code sample:
          String str = "HE&LLO";
          char ch = '&';
          if ( str.indexOf( ch ) == -1 ) {
               System.out.println("Character is NOT Present !" );
          } else {
               System.out.println("Character Present at position: " + (str.indexOf(ch) + 1));
Hope that helps!
Smita

Similar Messages

  • Searching for percent character (%) in a string

    Hi All,
    A strange request from one of our developers that I have not come across before.
    Is there a way to search for a percent character (%) in a string and also use the wildcard special character (%)?
    i.e. to return all values with a percent character (%)
    e.g. select column1 from table1 where column1 like '%%';
    When I do this all records are returned.
    Regards!!

    or use an INSTR function.If INSTR comes, can REGEXP be far behind ? - Ode to the Warren Tolentino... ;)
    test@ORA10G>
    test@ORA10G> @ver1
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    test@ORA10G>
    test@ORA10G> with t as
      2   (select 'the percentage (%) determines the final results' remarks from dual union all
      3    select 'otherwise non at all' remarks from dual)
      4  select * from t
      5  where regexp_like (remarks,'%');
    REMARKS
    the percentage (%) determines the final results
    test@ORA10G>
    test@ORA10G> with t as
      2   (select 'the percentage (%) determines the final results' remarks from dual union all
      3    select 'otherwise non at all' remarks from dual)
      4  select * from t
      5  where regexp_instr (remarks,'%') > 0;
    REMARKS
    the percentage (%) determines the final results
    test@ORA10G>
    test@ORA10G>pratz

  • Checking for '.' character

    Hi,
    I am developing a pogram that calculates the factorial of a number. I need to check if the user has typed in a decimal point ,., in the text field( this is because real numbers do not have a factorial)
    thankx in advance...

    import java.io.*;
    class MadBull {
    public static void main(String[] args) throws IOException {
    char[] exception = {'.','-'};
    boolean flag=false;
              int axilleas=0;
              BufferedReader br;
    br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter a digit");
    String harris;
    harris = br.readLine();
    System.out.println(harris);
    /*for(int i=0;i<harris.length();i++) {
                   if(!Character.isDigit(harris.charAt(i))) {
    if(flag==false)
                        if(((harris.charAt(0)==exception[1])) && (Character.isDigit(harris.charAt(1)))) {
    axilleas++;
    flag=true;
    continue;
    if(harris.charAt(i)==exception[0])
    continue;
                        System.out.println("The info you have entered is not a number");
    return;
    System.out.println("The info you have entered is a " +( axilleas==0 ? "number" :"negative number"));
    int i=0;
    boolean milan=true;
         while(i<harris.length()) {
    if((Character.isDigit(harris.charAt(i))) || (harris.charAt(i)==exception[0]) ||
              (harris.charAt(i)==exception[1]))
    i++;
    else {
    System.out.println("The info is not a number");
    milan = false;
    break;
    if(milan)
    System.out.println("The info is a number");
    }

  • Checking for an element in a string from another string

    Hi Guru's,
    I have 2 comma seperated strings. Say like this.
    a VARCHAR2(100) := '1,2,3,4,5,6,7,8,9,10';
    b VARCHAR2(100) := '2,6,9';
    My requirement is like I want to check the string a, whether it has any of the element in b. I am trying to use the regular expression. But I was not able to do it.
    Kindly help me.
    Regards,
    VJ

    SQL> var cur refcursor
    SQL> declare
       a              varchar2 (100) := '1,2,3,4,5,6,7,8,9,10';
       b              varchar2 (100) := '2,6,9';
    begin
       open :cur for 'select column_value common
            from table (sys.dbms_debug_vc2coll (' || a || ') multiset intersect sys.dbms_debug_vc2coll (' || b || '))';
    end;
    PL/SQL procedure successfully completed.
    SQL> print
    COMMON                                                                                                                           
    2                                                                                                                                
    6                                                                                                                                
    9                                                                                                                                
    3 rows selected.

  • Check for Alpha character

    I have a field that has data that looks like this
    12 H
    2 C
    4
    412 L
    32
    125
    14 H
    I need to create a formula field that Checks to see if the field contains a Alpha character
    If yes field = Abnormal
    If No field = Normal
    I know that chr(048) to chr(057) = Numeric characters but I don't know how to apply this to a formula.
    Thanks
    Steve

    You can use the NumericText (str) function.
    NumericText (123) returns true
    NumericText (1A) returns false

  • Find and print illegal character in a string using regexp

    I have the following simple regexp that checks for illegal characters in a string:
    String regexp = ".*([\\[\\];]+|@).*"; // illegal: [ ] ; @
    String input = "Testing [ 123";
    System.out.println(Pattern.matches(regexp, input));How can I find and print the character that is invalid??
    I've tried using the Matcher class togheter with Pattern but cant get it to work. :(
    Like this:
    Pattern pattern = Pattern.compile(regexp);
    Matcher matcher = pattern.matcher(input);
    matcher.lookingAt();
    int matchedChar = matcher.end();
    if (matchedChar < input.length()) {
        String illegalCharFound = String.valueOf(input.charAt(matcher.end()));
        System.out.println(illegalCharFound);
    }What am I doing wrong?

    1. You call lookingAt(), but you don't check its return value, so you don't know if the regex actually matched.
    2. matcher.end() returns the index of the character following whatever was matched, assuming there was a match (if there wasn't, it will throw an exception). So either it will point to a legal character, or you'll get a StringIndexOutOfBoundsException because an illegal character was found at the end of the input. The start() method would be a better choice, but...
    3. Your regex can match multiple consecutive square brackets or semicolons (and why not put the at-sign in the character class, too?), but you're acting like it can only match one character. Even if there is only one character, group(1) is an easier way to extract it. Also, if there are more than one (non-consecutive) illegal characters, your regex will only find the last one. That's because the first dot-star initially gobbles up the whole input, then backtracks only as far as it has to to satisfy the rest of the regex. If your goal is to provide feedback to whoever supplied the input, it's going to be pretty confusing feedback. You should probably use the find() method in a loop to pick out all the illegal characters so you can report them properly.

  • Want to know how to check for new line character in text file

    Hi All,
    I`m trying to read data from text file. However I`m not sure whether the data is in 1st line or nth line. Now I`m trying to read the text from the readline. But if text is "" and not NULL then my code fails. So I want to know how to check for new line character and go to next line to find the data. Please help.
    Thanks
    static int readandwriteFile(Logger logger,String filepath){
              BufferedWriter out = null;
              BufferedReader in = null;
              File fr = null;
              int get_count = 0;
              try     {
              if(new File(filepath).exists())
              fr= new File(filepath);
                        System.out.println("FileName: "+fr);
                   if(fr != null){
    in = new BufferedReader(new FileReader(fr));
                             String text = in.readLine();
                             if(text != null){
                             get_count = Integer.parseInt(text);
                             in.close();
                             else{
                                  get_count = 0;
         else{                    
    out = new BufferedWriter(new FileWriter(filepath));
         out.write("0");
                out.close();
                   }          //Reading of the row count file ended.
              catch(Exception e) {
                   e.printStackTrace();
              finally {
                   try{               if (in != null) {
                             in.close();
              if (out != null) {
                             out.close();
              catch(Exception e) {
                        e.printStackTrace();
              return get_count;
         }

    You are calling the readline() only once which means you are reading only the first line from the file...
    Use a loop (Do-While preferably)
    do{
    //your code
    }while(text == "")

  • 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

  • Checking for Paragraph sign / Return Character with indexOf()

    Hello all
    Al want to use String.indexIf() method to check for any Paragraph signs, or Return characters in a string, then delete or change them.
    I already tried the following, without success!
    int index = myAddress.indexOf('\r');
    and ('\n')
    Please help
    Thanks in advance
    Jaco

    just try to use a StringBuffer or the more diffcult way put the string into a StringTokenizer and set for delimitters all the paragraphs and whitespaces and then tokenize the string. You just have to determine the length of the splitstring and then you know where the characters are you look for

  • Best Way to Check for same Word in string?

    If I have an array of words, would the best way to check for the same word be to use 2 for loops?

    Huh?
    Sounds like homework...
    What is a word? Presumably a String.
    For equality of Strings you use...
        String s1 = ....
        String s2 =....
        if (s1 == s2) { equal depending on null case
        else if ((s1 != null) && (s1.equals(s2))) { equal }
    For the case of checking one array to another....
          while items in array1
                 get itema from array1
                      while items in array2
                           get itemb array2
                                  is itemb equal (see above) to itema
                                         yes - then do something

  • Checking for string

    i now doing a student system.
    Accepting student number ....
    do
    System.out.println("Student Number:");
    s =in.readLine();
    student_no =Integer.parseInt(s);
    if(student_no<10000||student_no>100000)
    System.out.println("Invalid student number.");
    studentNo_valid = true;
    else break;
    }while(studentNo_valid);
    Student had to enter their student number between 10000 - 99999
    my Question is how to use try and catch to check if that when student enter string .. it will give warning to student

    Look at
    Integer.parseInt
    new Integer(String)
    and java.text.DecimalFormat
    and pick the one that works for you.

  • Touch Events: How can I check for a button being pressed while another button is being held down?

    Hello,
    I'm trying to check for a button being pressed while another is down through Touch.  In my case, I' m making a game and I need for a button to make the character jump.  However, when I hold down right, I notice that the jump button becomes somewhat unresponsive and I have to press it twice or more to get it to trigger, as opposed to just pressing the jump button by itself with nothing held down which works fine.  I'm testing this on my Motorola Droid 2.
    Here is some of my code that demonstrates text instead of my character moving around:
    package  {
         import flash.events.TouchEvent;
         import flash.ui.Multitouch;
         import flash.ui.MultitouchInputMode;
         public class Document extends MovieClip {
               Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
               private var controls:BottomBar;
               private var debugText:String;
               public function Document() {
                    addIngameGUI();
               private function addIngameGUI(){
                    controls = new BottomBar();
                    controls.y = stage.stageHeight - controls.height;
                    addChild(controls);
                    controls.aBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.bBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.leftArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.rightArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
             private function testBtns(event:TouchEvent){
                   debugText.text = event.target.name;
    What am I doing wrong?  Is there a better approach?
    Thank you in advance.

    Hello,
    I'm trying to check for a button being pressed while another is down through Touch.  In my case, I' m making a game and I need for a button to make the character jump.  However, when I hold down right, I notice that the jump button becomes somewhat unresponsive and I have to press it twice or more to get it to trigger, as opposed to just pressing the jump button by itself with nothing held down which works fine.  I'm testing this on my Motorola Droid 2.
    Here is some of my code that demonstrates text instead of my character moving around:
    package  {
         import flash.events.TouchEvent;
         import flash.ui.Multitouch;
         import flash.ui.MultitouchInputMode;
         public class Document extends MovieClip {
               Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
               private var controls:BottomBar;
               private var debugText:String;
               public function Document() {
                    addIngameGUI();
               private function addIngameGUI(){
                    controls = new BottomBar();
                    controls.y = stage.stageHeight - controls.height;
                    addChild(controls);
                    controls.aBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.bBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.leftArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.rightArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
             private function testBtns(event:TouchEvent){
                   debugText.text = event.target.name;
    What am I doing wrong?  Is there a better approach?
    Thank you in advance.

  • Carriage return in textarea - how do I check for and remove it???

    I have an html form that has a <textarea> element for user input. I work mainly with Java and some JavaScript. Since carriage returns are permitted in a <textarea> element, upon retrieving the value submitted, my Java and/or JavaScript variables contain carriage returns as well, making the values incomplete.
    For Example :
    String dataSubmitted = request.getParameter("formInput");
    <script language="JavaScript">
    var textValue = "<%=dataSubmitted%>";
    ....//do other stuff
    </script>When I view the source of my JSP page, the above statement of code looks like this:
    var textValue = "This is some text that
    I submitted with a carriage return";I'm putting the text submitted through this form into a mysql database, and when I pull up the values I find that it has recorded the carriage return as well. There is an actual symbol representing a carriage return in the db field.
    What I'd like to do is use some Java code to go through each character of the String and find and remove the carriage return, perhaps replacing it with an empty space instead. But how do I check for a carriage return in a String variable?
    Also, is there a way to use JavaScript to alert the user when the carriage return button is pressed when they're in the <textarea>?
    Any input is appreciated,
    Thank You,
    -Love2Java

    What I'd like to do is use some Java code to go through
    each character of the String and find and remove the
    carriage return, perhaps replacing it with an empty
    space instead. But how do I check for a carriage return
    in a String variable?The carriage return is represented by the \r. Generally there is also a newline, the \n. You can use String#replaceAll() to replace occurences of them by a space.
    string = string.replaceAll("\r\n", " ");
    Also, is there a way to use JavaScript to alert the user
    when the carriage return button is pressed when they're
    in the <textarea>?You can capture keys using the 'onkeypress' attribute. The keyCode of a the return key is 13. So simply catch that:<textarea onkeypress="if (event.keyCode == 13) alert('You pressed the return button.'); return false;"></textarea>The return false prohibits the linebreak being inserted. If you remove that, then it will be inserted anyway.

  • Checking for Palindrome, is there a better way?

    Hi all,
    i m pasting the code which checks whether its a Palindrome or not. I am sure someone here could come up with some better way. I'll be obliged if they point out the changes.
    //Class PalindromeBeta
    public class PalindromeBeta{
         private static String s;
         public PalindromeBeta(){
         public static boolean isPalindrome(String as){
              s= as;
              int string_length = s.length();
              int stop_index = (int)(string_length/2);
              int start_index = 0;
              int end_index = string_length;
              int second_index = 1;
              if (string_length == 1)
              return false;
              else{
                   do{
                        if(s.substring(start_index,second_index).equalsIgnoreCase(s.substring((end_index-1), end_index))){
                             start_index++;
                             end_index--;
                             second_index++;
                        else
                        return false;
                   while(start_index != stop_index);
                   return true;
    //Class P7_16 with the main() method     
    public class P7_16beta{
         public static void main(String[] args){
              ConsoleReader console = new ConsoleReader(System.in);
              PalindromeBeta pd = new PalindromeBeta();
              boolean done = false;
              do{
                   System.out.println("Enter a String(Q to quit)");
                   String input = console.readLine();
                   if (input.equalsIgnoreCase("Q"))
                   done = true;
                   else if(pd.isPalindrome(input) == true)
                   System.out.println("It is a Palindrome");
                   else
                   System.out.println("It is not a Palindrome");
              while (done == false);
    //Class ConsoleReader , a hepling class for reading input
    import java.io.*;
    public class ConsoleReader
         private BufferedReader reader;
         public ConsoleReader(InputStream instream)
         reader = new BufferedReader(new InputStreamReader(instream));
    public String readLine()
    String inputLine ="";
    try
              inputLine = reader.readLine();
    catch(IOException e)
    System.out.println(e);
    System.exit(1);
    return inputLine;
    public int readInt()
         String inputString = readLine();
    int n = Integer.parseInt(inputString);
    return n;
    public double readDouble()
         String inputString = readLine();
    double x = Double.parseDouble(inputString);
    return x;
                        

    I'm posting my little code here: It compares every character in the string. It's not the faster way, but I think it's still very reliable.
    import java.io.*;
    class palindromo {
         public static void main (String [] args) throws Exception {
              String test = args[0];
              boolean result = true;
              if (test.length() <= 1)
                   result = false;
              else {
                   int end, begin;
                   begin = 0;
                   end = test.length() - 1;
                   if ((test.length())%2 == 0) {
                        while (begin < end) {
                             if (test.charAt(begin) != test.charAt(end)) {
                                  result = false;
                                  break;
                             begin++;
                             end--;
                   else {
                        int medio = (test.length() ) / 2 + 1;
                        while (begin < medio && end > medio) {
                             if (test.charAt(begin) != test.charAt(end)) {
                                  result = false;
                                  break;
                             begin++;
                             end--;
              System.out.println("The fact that the string is a palindrome is " + result);
         

  • [JS - CS3]  Not able to add 'Superscript' style to a character within a string

    Hello fellow experts...
    I'm stuck with trying to change the style of a character from Normal to Superscript!
    b Situation:
    I have a string - 'myCourseTitle' - that has both CharacterStyles & ParagraphStyles applyed and could include the following character/Word:
    > '®' (Character)
    'OperateIT' (Word)
    b Requirements:
    I am wanting to add the style 'Superscript' to both the '®' characters and 'IT' from the words 'OperateIT', while keeping their initial CharacterStyles & ParagraphStyles!
    b My Starting Block:
    if (myCourseTitleField.editContents == ""){
    var myCourseTitle = "-no title has been defined-";
    }else{
    var myCourseTitle = myCourseTitleField.editContents;
    // The contents should now be checked for '®' characters and 'OperateIT'
    // And set to Superscript if found!
    if (myCourseTitle.indexOf("®") != 0){
    alert("Registered Trade Mark '®' found in Course Title at position:"+myCourseTitle.indexOf("®")+"\rThis will be set to 'Superscript' formatting", "WARNING '®' within Course Title",)
    I have tried many scripts, including the attached sample 'FindChangeByList.jsx' script - but to no avail!
    Can anyone help me - point me in the right direction to start looking?
    Thanks in advance
    Lee

    Hi Lee,
    In the example, you're trying to apply InDesign formatting to a JavaScript string (from an InDesign dialog box text field). That won't work, because the JavaScript string doesn't know anything about InDesign text objects.
    I'm assuming, however, that what you want is to change the formatting of the text on your page. To do that, you can use the findText method on the text, story, or document. Here's an example (the relevant part is the "mySnippet" function--the rest is just setting up an example):
    main();
    function main(){
    mySetup();
    mySnippet();
    function mySnippet(){
    //Clear find text preferences.
    app.findTextPreferences = NothingEnum.nothing;
    app.changeTextPreferences = NothingEnum.nothing;
    app.findTextPreferences.findWhat = "®";
    app.changeTextPreferences.appliedCharacterStyle = app.documents.item(0).characterStyles.item("superscript");
    app.documents.item(0).changeText();
    //Reset find/change text preferences.
    app.findTextPreferences = NothingEnum.nothing;
    app.changeTextPreferences = NothingEnum.nothing;
    //Reset find/change GREP preferences.
    app.findGrepPreferences = NothingEnum.nothing;
    app.changeGrepPreferences = NothingEnum.nothing;
    //There's probably a way to do this in a single pass, but I'm short on time...
    app.findGrepPreferences.findWhat = "\\l(?<=)IT";
    app.changeGrepPreferences.appliedCharacterStyle = app.documents.item(0).characterStyles.item("superscript");
    app.documents.item(0).changeGrep();
    app.findGrepPreferences.findWhat = "\\l";
    app.findGrepPreferences.appliedCharacterStyle = app.documents.item(0).characterStyles.item("superscript");
    app.changeGrepPreferences.appliedCharacterStyle = app.documents.item(0).characterStyles.item("[None]");
    app.changeGrepPreferences.position = Position.normal;
    app.documents.item(0).changeGrep();
    app.findGrepPreferences = NothingEnum.nothing;
    app.changeGrepPreferences = NothingEnum.nothing;
    //mySetup simply takes care of setting up the example document.
    function mySetup(){
    var myDocument = app.documents.add();
        var myPage = app.activeWindow.activePage;
    //Create a text frame on page 1.
    var myTextFrame = myPage.textFrames.add();
    //Set the bounds of the text frame.
    myTextFrame.geometricBounds = myGetBounds(myDocument, myPage);
    //Fill the text frame with placeholder text.
    myTextFrame.contents = TextFrameContents.placeholderText;
    myTextFrame.insertionPoints.item(0).contents = "OperateIT®\r";
    myTextFrame.paragraphs.item(-1).insertionPoints.item(0).contents  = "OperateIT®\r";
    var myHeadingStyle = myDocument.paragraphStyles.add({name:"heading"});
    var mySuperscriptStyle = myDocument.characterStyles.add({name:"superscript", position:Position.superscript});
    function myGetBounds(myDocument, myPage){
    var myPageWidth = myDocument.documentPreferences.pageWidth;
    var myPageHeight = myDocument.documentPreferences.pageHeight
    if(myPage.side == PageSideOptions.leftHand){
      var myX2 = myPage.marginPreferences.left;
      var myX1 = myPage.marginPreferences.right;
    else{
      var myX1 = myPage.marginPreferences.left;
      var myX2 = myPage.marginPreferences.right;
    var myY1 = myPage.marginPreferences.top;
    var myX2 = myPageWidth - myX2;
    var myY2 = myPageHeight - myPage.marginPreferences.bottom;
    return [myY1, myX1, myY2, myX2];
    Thanks,
    Ole

Maybe you are looking for