Changing 1 character in a string

following on from my last question...
is there an easy way to set the value of one particular character at a certain index in a string? i'm suprised there's no setChar(index, char) kind of method in String.

You could always roll-your-own, although this doesn't really change the string, it creates a new string (this e.g. is 1-based, adj if you want 0-based)
class testing
  public static void main(String args[])
    String str = "Hello World";
    str = setChar(str,1,'W');
    System.out.println(str);
    System.exit(0);
  private static String setChar(String originalString, int position, char newChar)
    String newString = originalString.substring(0,position-1) + newChar +
                       originalString.substring(position);
    return newString;
}

Similar Messages

  • Changing one character in a string...how hard can it be...???

    Hey guys,
    I posted something the other day about changing a binary string to one complement. Well, now I want to change that again to the two's complement of the same number.
    The (messy) code I got so far is as follows:
    import java.util.*;
    class twosComplement {
      public static void main(String[] args) {
          Scanner reader = new Scanner(System.in);
          String binary;
          String i = "0";
          String j = "1";
          System.out.println("Enter a binary String:");
          binary = reader.nextLine();
       //   int x = 15;
       // String binary = Integer.toBinaryString(x);
       // binary = ("00000000"+binary).substring(8-binary.length());
        System.out.println("Your binary number is " +binary);
        String complement = binary.replaceAll("0","x").replaceAll("1","0").replaceAll("x","1");
        System.out.println("One's complement of your binary number is " +complement);
        int n = 0;
        int k = binary.length()-n;
        String m = charAt(k);
        if (charAt(k).equals(i)) binary.replace(charAt(k), j);
        else n++;
        System.out.println(binary);
    //    do {k++; }
    //    while (charAt(k).equals(i)) 
        private static String charAt(int k) {
            throw new UnsupportedOperationException("Not yet implemented");
        }the bit at the bottom is something netbeans kindly offered to create for me, it cut out a few syntax errors but didn't quite get the program to work.
    I'm pretty sure the root of my troubles is coming from the use of the "charAt" method, which as far as i know, would be better used with arrays, but I don't know of another way to sort this stuff...
    any help would be muchly appreciated.
    Aaron.

    ok. The following is a section from the original code (see above). I was hoping this code would take a binary string (ie, '1010101') and change the least significant bit which is a '0' to a '1'. The following section is my attempt at solving this problem, but as I run it, I encounter errors. I've been studying java for 2 months. I would like to know if anybody knows WHY this isn't working, and could offer an alternative method (as I've already stated, I think the use of the method 'charAt' is the main problem)
    int n = 0;
        int k = binary.length()-n;
        String m = charAt(k);
        if (charAt(k).equals(i)) binary.replace(charAt(k), j);
        else n++;
        }Is that better?

  • How to change a certain character in a string?

    hi,
    how can i change a certain character in a string. Lets say i have a string s="0000" and i want to change the last character (s.charAt(3)) to be a 1. how would i go about doing so?

    i did this
    num.charAt(lspace) = s.charAt(i+1);and am getting an errorThat's because you can't do that. You should go for one of the alternatives mentioned above.
    Kaj

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

  • Update one character in a string

    Hello Experts,
    I would like to update a character in a string in a column using update statment.
    For eg in table a1 column has "ABCDEF", I would like change "C" with "c" . After change the a1 value should be "ABcDEF".
    Any help will be highly appreciated.
    Regards,
    Rashida

    Use Translate Function
    Example
    SQL> select translate('ABCDEF','C','c') from dual ;
    TRANSL
    ABcDEF
    Or Replace Function
    Exmaple
    SQL> select replace('ABCDEF','C','c') from dual ;
    REPLAC
    ABcDEF
    for table with column a1
    update a1 set col1 =  replace(col1,'C','c') ;
    OR
    update a1 set col1 =  translate(col1,'C','c') ;

  • Newline character in a String

    Hi,
    How can i introduce a newline character while displaying a string using string functions in a report..
    My requirement is, i need to replace a particular character with a newline character in a string using replace function
    Can anyone help me
    Thanks in advance..

    Hi,
    Try this,
    REPLACE(Table.ColumnName, 'StringOrCharacterToReplace', '[br]')
    *replace [ and ] with < and > in br tag. Change the data format of the column to HTML
    Rgds,
    Dpka

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

  • 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 change the Color of a string using swings/awt concept.

    Hi friends,
    How can i change the Color of a string.
    For ex:
    If i have a string "Welcome to the Java World",I want one particular Color for the string "Welcome to the" and a different Color to the "Java World" string.
    So please kindly help me out to resolve this issue.
    Thanking u in advance.

    "Text Component Features"
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html

  • 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

  • Changing database character set from US7ASCII to AL32UTF8

    Our database is running on Oracle database 10.1.0.4.0 (AIX) The following are its parameters:
    SQL> select value from NLS_DATABASE_PARAMETERS where parameter='NLS_CHARACTERSET';
    VALUE
    US7ASCII
    We would like to change the database character set to AL32UTF8. After following Metalink notes: 260192.1 (which helped us resolve "Lossy" and "Truncated" data, the final output of the CSSCAN utility is:
    [Scan Summary]
    All character type data in the data dictionary are convertible to the new character set
    All character type application data are convertible to the new character set
    [Data Dictionary Conversion Summary]
    The data dictionary can be safely migrated using the CSALTER script
    We have no (0) Truncation and Lossy entries on the .txt file. We only have Changeless and Convertible. Now accdg to the documentation, we can do a FULL EXP and FULL IMP. But it did not detail how to do the conversion on the same database. The discussion on the document tells how to do it from one database to another database. But how about on the same database?
    We cannot use CSALTER as stated on the document.
    (Step 6
    Step 12
    12.c) When using Csalter/Alter database to go to AL32UTF8 and there was NO "Truncation" data, only "Convertible" and "Changeless" in the csscan done in point 4:)
    After performing a FULL export of the database, how can we change its character set? What do we need to do the the existing database to change its character set to AL32UTF8 before we import back our dump file into the same database?
    Please help.

    There you are! Thanks! Seems like I am right in my understanding about the Oracle Official Documentation. Thanks!
    Hmmmmm...when you say:
    *"you can do selective export of only convertible tables, truncate the tables, use CSALTER, and re-import."*
    This means that:
    1. After running csscan on database PROD, i will take note of the convertible tables in the .txt output file.
    2. Perform selective EXPORT on PROD (EXP the convertible tables)
    3. Truncate the convertible tables on PROD database
    4. Use CSALTER on PROD database
    5. Re-import the tables into PROD database
    6. Housekeeping.
    Will you tell me if these steps are the correct one? Based on our scenario: This is what i have understood referring to the Official Doc.
    Am i correct?
    I really appreciate your help Sergiusz.

  • 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 do I change a character in the document to another character in one command?

    How do I change a character in the document to another character in one command?

    You mean everywhere? Use Find/Change

  • 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

Maybe you are looking for