Replacing a char with string in a string buffer.

Hi all,
I have a huge xml file. Need to search for the following characters: ^ & | \ and replace each character with \T\ \F\ \B\ \C\ respectively.
i.e. ^ must be replaced with \T\
& must be replaced with \F\
I see that it can be done in case of String using replaceAll() but have no clue about achieving using the stringbuffer??
Any help is higly appeciated.
Thanks in advance.

Hi all,
I have a huge xml file. Need to search for the
following characters: ^ & | \ and replace each
character with \T\ \F\ \B\ \C\ respectively.
i.e. ^ must be replaced with \T\
& must be replaced with \F\
I see that it can be done in case of String using
replaceAll() but have no clue about achieving using
the stringbuffer??
Any help is higly appeciated.
Thanks in advance.here the solution for your problem:
example code as follows,
     StringBuffer stringBuffer = new StringBuffer("your xml content");           
            String xmlString = stringBuffer.toString();
            char[]  xmlCharArray =  new char[];
            xmlString.getChars(0, xmlString.length()-1, xmlCharArray, 0);
           StringBuffer alteredXmlBuf = new StringBuffer();
            for(int i=0; i<xmlCharArray.length; i++){
                           if( xmlCharArray[i] == '^'){
                                  alteredXmlBuf.append(" \\T\\") ;
                           }else if(xmlCharArray[i] == '&'){
                                  alteredXmlBuf.append(" \\F\\") ;
                           }else if(xmlCharArray[i] == '|'){
                                  alteredXmlBuf.append(" \\B\\") ;
                           }else if(xmlCharArray[i] == '\'){
                                  alteredXmlBuf.append(" \\C\\") ;
                           }else {
                                   alteredXmlBuf.append(xmlCharArray);
now alteredXmlBuf StringBuffer object contains your solution.

Similar Messages

  • How to replace one char with two chars in email address policy?

    I very much like to replace the 'ß' char in the surname with 'sz'. However, applying filter '%rßsz%[email protected]' on 'Preußig' leaves me with '[email protected]'.
    So, how do I replace one char with two chars in email address policy?

    As far as I know, your only solution is to manually create such addresses instead of using e-mail address policy.
    Ed Crowley MVP "There are seldom good technological solutions to behavioral problems."

  • Replace last delimeter with "and" in a string in SSRS

    Hi,
    I want to replace last delimeter (comma) with and 
    in a string in SSRS 2008 R2.
    if there are more than one unit, and the Area of the units are different, then the area of each must must be listed separated by commas and ‘and’ before the last one.
    i.e.,
    Input string- Hi,Hello,HRU,
    Desired output- Hi,Hello and 
    HRU..
    how can I achieve this (and
    before last word) ?
    (suggest in SSRS or even in SQL)
    Rgds/-

    Your example seems to indicate you wish to substitute "and" for the second to last delimiter and ".." for the last. Is that the ask? Will there actually be a trailing delimiter on the input string?
    This can be done several ways: In the dataset, in an expression, using custom code.
    The approach for the dataset and expression are similar, just the language is different. Dataset will usually deliver better performance since the source is often a more powerful server (in the case of a SQL dataset).
    In an SSRS expression it might look like this:
    =Left(Fields!InputString.Value,InStrRev(Fields!InputString.Value,",")-1)+" and "+Right(Fields!InputString.Value,Len(Fields!InputString.Value)-InStrRev(Fields!InputString.Value,","))
    This assumes the input string is actually a field from your dataset but it could be anything. The Left piece gets the string that occurs before the last comma without the comma, then append " and ", then the Right expression gets everything after the last
    comma and appends it. If you will have a trailing delimiter, you could substitute the following formula anywhere you see Fields!InputString.Value:
    =Replace(Trim(Replace(Fields!InputString.Value,","," "))," ",",")
    Because Trim in an SSRS expression only trims leading and trailing spaces, the delimiters must be converted to a space. So this only works if there are no spaces in the original string. If the input is "Hi,Hello,How are you," the result of this formula will
    be "Hi,Hello,How,are,you" because the spaces between How, are and you will get replaced by ",". To handle embedded spaces makes the expression more complex. Assuming the input string is "Hi,Hello,How are you,":
    =Replace(Replace(Trim(Replace(Replace(Fields!InputString.Value," ","|"),","," "))," ",","),"|"," ")
    This expression uses 2 more replace statements. The innermost statement substitues "|" for the embedded spaces so they don't get replace with ",". You should use a character that you are sure will not appear in the string otherwise. Or use a sequence of
    characters like "|^|" that you are sure won't appear if any one character may possibly appear. The outermost Replace restores the "|" characters back to spaces.
    A code solution may be easier. Just wrap the below in a simple function:
    return str.Trim(",".ToCharArray()).Substring(0, str.Trim(",".ToCharArray()).LastIndexOf(",") - 1) + " and " + str.Trim(",".ToCharArray()).Substring(str.Trim(",".ToCharArray()).LastIndexOf(",") + 1);
    This is the VB.Net equivalent of the expressions above.
    "You will find a fortune, though it will not be the one you seek." -
    Blind Seer, O Brother Where Art Thou
    Please Mark posts as answers or helpful so that others may find the fortune they seek.

  • Replace one char with the other

    I am reading a path,when i use the system path with the \ slash in java its not compatible in windows,
    is there any facility in java for replacing the rightslash with the forward slash
    i.e when we encounter '/' i wanna to replace it with '\'
    sample code needed
    please help me
    thank in advance,
    with regards

    The java file handling code will work with paths containing forward slashes, even on windows. If you want to convert to backslashes before displaying to the user or calling native code, then something like the following should work:
    String myPath = "C:/Windows";
    myPath = myPath.replace('/', '\\');

  • Containers...replacing two chars with a string

    public static char[] translate(String string)
    Scanner sc=new Scanner(string);
    int x=0;
    char output[]=string.toCharArray();
    for(int i=0; i<output.length; i++)
    if (output=='[')
    if(output[i++]=='C')
    output[].remove(i);
    output[].remove(i++);
    output[].insert(output, i, 6);
    output[].fill(output, i, i+6, "char[]");
    return output;

    i apologize. i am unable to edit the code.
    i want to find and replace two contiguous chars, '[' and 'C' with the string "char[]" ...I have just found that remove, insert and fill do not exist in the char array...How can I edit this function to return a string after it's been edited?
    the code i posted returns compile errors: Firstclass.java:163: class expected
    output[].remove(i);
    ^
    Firstclass.java:163: not a statement
    output[].remove(i);
    ^
    Firstclass.java:164: class expected
    output[].remove(i++);
    ^
    Firstclass.java:164: not a statement
    output[].remove(i++);
    ^
    Firstclass.java:165: class expected
    output[].insert(output, i, 6);
    ^
    Firstclass.java:165: not a statement
    output[].insert(output, i, 6);
    ^
    Firstclass.java:166: class expected
    output[].fill(output, i, i+6, "char[]");
    ^
    Firstclass.java:166: not a statement
    output[].fill(output, i, i+6, "char[]");
    ^
    8 errors

  • How to replace the char values into numeric in my string?

    Hi Friends,
    I would like to Replace the Charecter values with numeric value in my string.
    Exp : first in my string I am having the value like this : 'ABCD1234' ( may be any char and num values ), and I want too get it by '99991234'.
    I mean How to replace the char values into numeric in my string?
    Thanks,
    Sridhar

    Hi Sridhar,
    I would like to Replace the Charecter values with numeric value in my string.
    Exp : first in my string I am having the value like this : 'ABCD1234' ( may be any char and num values ), and I want too get it by '99991234'.
    So, if i understand you correctly, you want to replace all characters in a string with 9 as in the above example, irrespective of position of the character, if so try with the below code.
    DATA: l_str TYPE string.
    l_str = 'ASKHSIUDNSBDKJSDH124312431243124saasdfsf'.
    REPLACE ALL OCCURRENCES OF REGEX '\D' IN l_str WITH '9'.
    IF sy-subrc EQ 0.
      WRITE: l_str. "Result will be 9999999999999999912431243124312499999999
    ENDIF.
    Regards,
    Chen
    Edited by: Chen K V on Jun 13, 2011 12:36 PM

  • How to replace mixed chars string

    Hi All,
    I want to replace mixed chars string from each row and want to replace with new string.
    Ex : The existing string might be in different cases like "Abc string", "abc string", "aBC string". I want to search for all these string types and want to replace with new string "Abc string".
    Could anyone give suggestions on this.
    Thanks,
    Prakash

    [url http://download.oracle.com/docs/cd/E11882_01/server.112/e26088/functions149.htm#i1305521]REGEXP_REPLACE supports case insensitive replacing.
    REGEXP_REPLACE(source_string,'abc string','Abc string',1,0,'i')The *'i'* specifies case insensitive replacing, so it will find all of "Abc string", "abc string", "aBC string" :-)

  • Function to replace/delete specific character(s) in a string

    Hi, experienced CVI guys,
    Are there some functions shipped with CVI to replace or delete specific characters in a string?
    For example, I want to replace all \/|- with an empty string, or to delete them. What can I do?  Loops are too complex.
    Original string:
    Erasing Device...
    \|/- \ \ \\|/-\|/ \
    Report
    07-Sep-2010, 08:04:55
    Result I want is
    Erasing Device...
    Report
    07-Sep-2010, 08:04:55
    Thanks.
    Solved!
    Go to Solution.

    labc:
    How generic do you want to make your filter?
    For our discussion, I'll call your series of characters a text spinner.  I'm assuming the number of characters in it may vary, but that the pattern is consistent in the respect: the spinner is made up of characters like \ / | -, each followed by the ASCII backspace (char) 8.  (That's 8 cast as a character, which is not the same as '8'.)  In your sample spinner pattern, every occurrence of the ASCII backspace is preceded by one of the spinner characters.  Let's assume that this pattern is constant.
    So what I'd do is search through your input string (yes, using a loop) and copy the input string byte by byte to an output string.  If you find an ASCII backspace in the input string, skip it, and overwrite the last character in the output string (which is one of the spinner characters) with the next character in the input string.
    Yes, you are using a loop, but it's not too complex.
    Here's the whole loop, written as a function.
    // filterSpinner function to strip the text spinner characters out of a string.
    // The text spinner is made up of \ / | - characters separated by (char) 8 (ASCII backspace)
    int filterSpinner(char *inputString, char *outputString)
     int inputPtr, outputPtr = 0;
     // walk though the input string
     for (inputPtr = 0; inputPtr < strlen(inputString); inputPtr++, outputPtr++)
      // search for the ASCII backspace character that's part of the spinner
      if (inputString[inputPtr] == 8)
       // if the ASCII backspace is found,
       inputPtr++;  // increment the inputString pointer to skip the backspace
       outputPtr--; // decrement the outputString pointer to overwrite
           // the spinner character that preceded the backspace
      outputString[outputPtr] = inputString[inputPtr];
     outputString[outputPtr] = '\0';
     return 0;
    You'll also find an attached CVI program which uses it on your sample string.
    Attachments:
    FilterSpinner1.zip ‏5 KB

  • Replacing a set of characters from a string in oracle sql query

    I want to replace a set of characters ( ~    !     @    #     $     %     ^     *     /     \     +    :    ;    |     <     >     ?    _  ,) from a STRING in sql
    select 'TESTING ! ABC 123 #'
    FROM DUAL;
    What is the best way to do it? Please provide examples also.

    What is your expected output... The query I posted just removes them, it never replaces them with spaces..your string already has space.. if you want to remove space as well .. try this...
    SELECT TRANSLATE ('TESTING ! ABC 123 #', '-~!@#$%^*/\+:;|<>?_, ', ' ') FROM DUAL;
    Output:
    --TESTINGABC123
    Else post your expected output..
    Cheers,
    Manik.

  • How to fix a problem with the order of strings in a JSON response for a CFHTTP request?

    Good morning, guys! (It's 10:50 a.m. in Brazil)
    First of all, I'm still new at CF and my questions may seem too much silly and my English's not the best, so, please be patient with me. hehe
    Well, I'm accessing a link via CFHTTP that gives me a JSON response. I'm not familiar with JSON yet, so I'm working it as a string and using string functions (Find,RemoveChars,Replace,etc), but it happens to me that I'm receiving a certain kind of order of the strings list from the JSON when I access it directly from the browser and other kind of order totally different when I access it from the CFHTTP.
    I only figured it out because I was working at home with my code and there everything went just fine as expected. Then I brought to my job to develop a little bit more as soon as I get a free time and here my code doesn't work anymore. When I took a look at the JSON by a CFOUTPUT, I realized the strings were in a different order.
    Does anyone know why is it happening?
    Link to the JSON: http://sigmine.dnpm.gov.br/ArcGIS/rest/services/extra/dados_dnpm/MapServer/0/query?text=83 0620/2012&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelInter sects&where=&returnGeometry=true&outSR=&outFields=FID,Shape,PROCESSO,ID,NUMERO,ANO,AREA_HA ,FASE,ULT_EVENTO,NOME,SUBS,USO,UF&f=pjson
    Basic code simplified to find out that the order of strings were coming different when access by CFHTTP:
    <cfhttp url="#URLAbove#" method="get" result="DadosDoDNPM" charset="utf-8" timeout="10000" />
    <cfset DadosJSON = deserializeJSON(DadosDoDNPM.FileContent) />
    <cfif arrayLen(DadosJSON.features)>
        <cfset CodigoFonteJSON = ToString(serialize(DadosJSON.features)) />   
        <cfoutput> #CodigoFonteJSON# </cfoutput>
    </cfif>
    Is there a way to fix it and to make my code work everywhere?
    If it matters, I use Railo at home and at my job.
    Since now, I thank you.

    When you deserialize JSON data, ColdFusion converts it into native structures and arrays (roughly equivalent to JavaScript objects and arrays).  In ColdFusion, structures are unordered (that is, they don't maintain keys in any particular ordered sequence).
    This really shouldn't be a problem though, at least not if you just want to work with the data contained in the deserialized JSON structure.  So DadosJSON should be a native ColdFusion structure, and you can interact with it like any other structure in ColdFusion.  In fact, you should not have to re-serialize it at all unless you need to send it to an external application using JSON.
    Why are you reserializing the data?  And why use serialize() instead of serializeJSON()?
    -Carl V.

  • Problem with code: reading a string

    Hi,
    I am very new to java so excuse my naivety. i need to write some code which will decode an encrypted message. the message is stored as a string which is a series of integers which. Eg. Nick in this code is 1409030110 where a = 1, b = 2,... and there is a 0 (zero) after every word. at the moment the code only goes as far as seperating the individual characters in the message up and printing them out onscreen.
    Heres the code:
    int index = 0;
    while(index < line.length() - 1) {
    char first = line.charAt(index);
    char second = line.charAt(index + 1);
    if(second == 0) {
    char third = line.charAt(index + 2);
    if(third == 0) {
    System.out.print(first + "" + second);
    index = index + 3;
    else {
    System.out.print(first);
    index = index + 2;
    else {
    System.out.print(first + "" + second);
    index = index + 3;
    Basically its meant to undo the code by reading the first two characters in the string then determining whether the second is equal to 0 (zero). if the second is 0 then it needs to decide whether the third character is 0 (zero) because the code could be displaying 10 or 20. if so the first two characters are recorded to another string and if not only the first is recorded. obviously if the second character is not a zero then the code will automatically record the first 2 characters.
    my problem is that the code doesnt seem to recognise the 0 (zero) values. when i run it thru with the string being the coded version of Nick above (1409030110) the outputted answer is 1490010 when it should be 149311. as far as i can see the code is right but its not working! basically the zeros are begin removed but i need each group of non-zero digits to be removed seperately so i can decode them.
    if anyone has understood any of this could you give me some advice, im at my wits end!
    Thanks, Nick

    Try something like this:
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.IOException;
    import java.util.Properties;
    public class SimpleDecoder
        /** Default mapping file */
        public static final String DEFAULT_MAPPING_FILE = "SimpleDecoder.properties";
        /** Regular expression pattern to match one or more zeroes */
        public static final String SEPARATOR = "0+";
        private Properties decodeMapping = new Properties();
        public static void main(String [] args)
            try
                SimpleDecoder decoder = new SimpleDecoder();
                decoder.setDecodeMapping(new FileInputStream(DEFAULT_MAPPING_FILE));
                for (int i = 0; i < args.length; ++i)
                    System.out.println("Original encoded string: " + args);
    System.out.println("Decoded string : " + decoder.decode(args[i]));
    catch (Exception e)
    e.printStackTrace();
    public void setDecodeMapping(InputStream stream) throws IOException
    this.decodeMapping.load(stream);
    public String decode(final String encodedString)
    StringBuffer value = new StringBuffer();
    String [] tokens = encodedString.split(SEPARATOR);
    for (int i = 0; i < tokens.length; ++i)
    value.append(this.decodeMapping.getProperty(tokens[i]));
    return value.toString();
    I gave your "1409030110" string on the command line and got back "nick". The SimpleDecoder.properties file had 26 lines in it:
    1 = a
    2 = b
    3 = c
    // etc;Not a very tricky encryption scheme, but it's what you asked for. - MOD

  • Replace String in a String

    How can I replace a String in a String ,for example :
    in the String "Hello World" replace Hello with Bye" ?
    Is there a class or code I can find for that purpose?

    use an utility method like this :
    I did not found an existing method doing this in java.lang.String or StringBufer
    public static String replaceFirstSubstring(
    String stringToSubstitute, String searchString, String replaceString) {
    if (stringToSubstitute == null) {
    return null;
    int prefixEndIndex = stringToSubstitute.indexOf(searchString);
    if (prefixEndIndex == -1) {
    return stringToSubstitute;
    int suffixStartIndex = prefixEndIndex + searchString.length();
    StringBuffer newString = new StringBuffer(stringToSubstitute.substring(0, prefixEndIndex));
    newString.append(replaceString).append(stringToSubstitute.substring(suffixStartIndex));
    return newString.toString();
    put it in a while if you need to replace more than 1 time

  • Java.lang.String:   How can we replace the list of characters in a String?

    String s = "abc$d!efg:i";
    s = s.replace('=', ' ');
    s = s.replace(':', ' ');
    s = s.replace('$', ' ');
    s = s.replace('!', ' ');
    I want to check a list of illegal characters(Ex: $ = : ! ) present in the String 's' and replace all the occurance with empty space ' '
    I feel difficult to follow the above code style.. Because, If list of illegal characters increased, need to add the code again to check & replace the respective illegal character.
    Can we refactor the above code with any other simple way?
    Is there any other way to use Map/Set in this above example?

    RTFM
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
    That document is almost perfectly useless for someone
    who is just starting to learn regexes. What they
    need is a good tutorial, and the best one I know of
    for Java programmers is the one at
    this site. When you're ready to move on from
    introductory tutorials, get the latest edition of
    Mastering Regular Expressions, by Jeffrey Friedl.Dear Uncle,
    maybe you want to read that document first before judging its usefulness. And just in case you can't be bothered, the following is an exact quote, which accidently happens to clearly explain the op's question on the usage of \\[\\] in sabre's regex:
    Backslashes, escapes, and quoting
    The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.
    It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
    Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.

  • Replace all occurrences of ENTER in a string

    Hi,
    I have a string which contains line breaks:
    '<HTML><HEAD>
    </HEAD>
    <BODY>'
    and it is shown to me in the debugger as:
    '<HTML><HEAD>#</HEAD>#<BODY>'
    Now I want to replace all line breaks in the string,
    but
    replace all occurrences of `#` in text with ' '.
    doesn't work.
    So if you have an idea how to replace the # symbol for Enter in a string please tell me ;).
    regards,
    Stefan

    Hi,
    Pls use
    replace all occurences of '#' in text with cl_abap_char_utilities=>newline.
    Eddy

  • To compare date with another date in string in siebel bip report

    Hi,
    In my rtf I am comparing a Date1 with a date in string i.e. '10-NOV-14'. If Date1 is less than '10-NOV-14' I am dispalying a certain text and if not another text.
    This condition is working fine if Date1 have 2014 values but if  Date1 cointains 2015 date than the mentioned condition is falling.
    Kindly suggest any solutions.
    Regards,
    Siddhika

    This example may help:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:param name="currentDate"/>
        <xsl:variable name="firstDate" select="concat(substring($currentDate, 1,4),substring($currentDate, 6,2),substring($currentDate, 9,2))"/>
        <xsl:template match="/">
            <xsl:apply-templates select="//item"/>
        </xsl:template>
        <xsl:template match="item">
            <xsl:variable name="secondDate" select="concat(substring(submissionDeadline, 1,4),substring(submissionDeadline, 6,2),substring(submissionDeadline, 9,2))"/>
            <xsl:choose>
            <xsl:when test="$firstDate &gt; $secondDate">
                <xsl:call-template name="late"/>
                </xsl:when>
                <xsl:when test="$firstDate &lt; $secondDate">
                    <xsl:call-template name="ontime"/>
                </xsl:when>
                <xsl:when test="$firstDate = $secondDate">
                    <xsl:call-template name="same"/>
                </xsl:when>
                <xsl:otherwise>Monkeys<br /></xsl:otherwise>
            </xsl:choose>
        </xsl:template>
        <xsl:template name="ontime">
            This is on time
        </xsl:template>
        <xsl:template name="late">
            This is late
        </xsl:template>
        <xsl:template name="same">
            This is on time
        </xsl:template>
    </xsl:stylesheet>

Maybe you are looking for

  • Conversion factor and batch management

    Dear gurus,           1) I want to mention conversion factor in material master but when I enter it with decimal i.e. 1 meter = 1.55 tone system is not permited the decimal what I can I do for it.            2) I want to mention my material in batche

  • HELP! I just updated my iphone 4s to the new ios7 software, and all of my photos have disappeared!!!

    Hi All, Having a slight panic.  I just updated my iphone 4s to the new software...was transferring my photos to my iphoto app on my macbook.  I then realised that ALL of my recent photos (including albums) were no longer in my camera roll etc.... I c

  • ITunes shuts down when I try to purchase songs

    When I click "buy album" it connects to the store, and then iTunes shuts down. It also shuts down when I try to "check for purchases." I am running the newest version of iTunes. It also did this with my previous version. Real Player also shuts down,

  • Can't Import songs from Pink CD. ( titled -Try This )

    Normally after inserting a cd itunes shows me that is sees the cd but when i insert Pink's CD (try this) Itunes does not see it. So i cannot put any songs onto my ipod. This cd has an enhanced section (video) is this why this cd cannot be seen by itu

  • Color artifacts in DNG files

    Hi, I've got a major issue with Adobe PS Lightroom DNG import on my Mac from my Canon EOS 5D Mark III. Any image converted to DNG file format is showing heavy color artifacts around edges, whereas the color of the object in focus is abruptly replaced