Modifying a string...

I'd like to modify a string. I wanna replace a substring of the original string to another substring. I was looked for a method in Java API, but i didn't find the perfect, because there is a replace(char,char) method, but i don't want to replace just 1 character. Please, help me. Thanks.

Since JDK 1.4 there is a [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)]replaceAll method that performs regex matching. This will return a new String and will not change the original one since String is an immutable class
Mike

Similar Messages

  • The "write key" configurat​ion file vi use of "trim string" prior to writing the data can modify any string data written.

    I tried to use the config VIs to record some front-panel settings for later restoration, one of which could be a single space character (part of a string parsing system).
    I soon discovered that whenever I tried to save that single-space value to an INI file, only a null string was saved.
    After doing some digging I discovered that buried in the Write Key vi is a worker vi called Config Data Modify that uses Trim String on the string data before it is written to the file and that's what was eating my string character. I don't know whether this is a bug or a feature but there are at least three ways to fix it.
    1) Assuming you want to leave the library VIs alone, you can pre-process any stings sent to "write key" to replace all spaces with "\20" and then post-process all strings read using "read key" to replace all instances of \20 with spaces.
      and if you don't mind modifying the library VIs, either to save/use under a different name or to stick back into the library in a modified state (caution - can cause problems when you move code to another machine with an un-modified library) then...
    2) You can yank the trim-string out of the Config Data Modify vi and hope that it does not have any undesirable side effects with regards to the other routines that use Config Data Modify (so far I have not found any in my limited testing)
    or
    3)  You can modify the string pre-processing vi, Remove Unprintable Chars, to add the space character to the list of characters that get swapped out automatically.
    Note that both option #1 (as suggested above) and option #3 will produce an INI file data entry that looks like    key="\20Hello\20World\20"   while option #2 produces an entry that looks like   key=" Hello World "
    The attached PDF contains screenshots of all this.
    Attachments:
    Binder1.pdf ‏2507 KB

    Hi Warren,
    there's a 4th option:
    Simply set the "write raw string" input of the write key function to TRUE
    This option only appears when a string is wired to that function!
    Just re-checked:
    I think it's a limitation of the config file format. It's text based and (leading) spaces in the value are "overseen" as whitespaces. So your next option would be to use quotes around your string with spaces...
    Message Edited by GerdW on 05-02-2009 08:32 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • How do I keep from highlighting terms in the search bar when I modify a string in the search bar--other than by clicking three to five times?

    I'm not talking about terms in the search results; I'm talking about terms in the search string in the search bar in the upper right corner. (Mine is set to use only Google.) When I've searched on a string and decide to modify the string for a second search (say, changing "Spanish architecture" to "Spanish architectural style"), clicking at the end of the search string first highlights the entire string and then, as I keep clicking, highlights various parts of the string. Sometimes it takes five clicks to get the highlighting to go away so I can start back-deleting normally instead of by entire word or phrase. The Google homepage doesn't do this, whereas all search engines in Firefox do it, so it's clearly a Firefox annoyance.

    Left click ONCE to get it's attention. After a moment, then do your work.

  • Modify XML string of a view before output

    Hi!
    I'm still working in the view IUICMD/CreatePerson, when you're in the CreatePerson.htm, you will found  
    DATA lv_xml TYPE string.
      lv_xml = controller->configuration_descr->get_config_data( ).
    In the string I can se all the layout for my view, is there method to work around with this string to change the properties of the atributes so I can change the layout dinamically?
    Reward points will be granted for useful answers!
    Thanks N' Best Regards
    Luís
    Edited by: Luis pérez on May 7, 2008 9:25 AM

    Hello Luis,
    The XML string is the result of the View Configuration you made yourself
    In the BSP WD Component Workbench (BSP_WD_CMPWB) you can find for each view of that component a tab called 'Configuration' where you can modify
    - what fields are visible on that page (add/remove fields)
    - how the fields are ordered on the field
    - how the fields look like (display length, ...)
    The results of that configuration is stored as XML in the system and called in the view (.htm) by the code you mentioned (lv_xml = controller->configuration_descr->get_config_data( ).) So if you want to change the layout of that specific view, just open the configuration tab of that view!
    If you still want more flexibility you can totally disable that line of code and program everything yourself in the view with either <htmlb> <crm_bsp_ic> or one of the other (or a combination of) BSP tags, like it was in CRM 5.0. SAP still uses that way of programming for some components, maybe take a look at them, then you'll see what I mean. (Open component BT126H_MAIL in the BSP_WD_CMPWB; then double click on the 'send_screen' view and open the 'send_screen.htm' in the right pane by double clicking on it, here you see that no XML is used, instead all visible components are coded using HTML and SAP tags)
    If you're not used to program in BOL / HTMLB I strongly suggest to use the SAP 'Configuration' XML mechanism. It saves you a huge amount of coding (and time)!
    Hope this makes things clear!
    Reward points if useful!
    Regards,
    Joost

  • Modifying a string in a DLL

    I am using the flexible DLL prototype adapter to pass a test stand string (local). I wish to modify the contents of the string within the body of my DLL 'C' Function.
    When I try to use a type that will allow the code to make the modifications on the test stand variable, Test Stand generates an error when it checks my type library.
    I have tried using the following string types in my code:
    LPCTSTR* pszString
    BSTR* pbstrString
    Both types generate a type not supported message in Test Stand.
    Is it possible to perform this action using test stand?

    Hi C_Test,
    A character string (char[]) can be modified inside a DLL call. Just as Ron said, to TestStand this is C String Buffer which is modifiable from the C DLL.
    Attached is a zipfile containing a sequence file (teststring.seq) which calls a Visual C++ 6 DLL that contains one function takes one input parameter (char mystring[1024]). The input string is modified, and the sequence file displays before and after message popups to show that this works.
    Regards,
    David Mc.
    National Instruments - Applications Engineeing
    Attachments:
    teststring.zip ‏261 KB

  • Have a JTextComponent directly modify a String

    I'm at a complete loss, here. What I need to do is have a JTextComponent basically display a String and any modifications to the text in the JTextComponent will mirror in the String - so it's like they're the same.
    I've tried several approaches to this...
    First try I used a custom DocumentListener (applied to the JTextComponent) which would intercept any changes and basically perform this:
    myString = documentEvent.getDocument().getText(0, documentEvent.getDocuiment().getLength());But this would cause dramatic slowdowns if the String contained in the Document was large, and on top of this, each time a character is inserted or removed in the Document, that code was run- even more slowdown!
    My second pseudo-try (I couldn't get it to work properly) involved PipedInput and PipedOutput streams. I read that it would be better to have a Thread dedicated to having the PipedInputStream receive data from the PipedOutputStream (configured to monitor the text in the JTextComponent). I didn't get this to work.
    Then I started reading up on StringWriter and StringReader. And then ByteArrayInput and Output classes.
    I couldn't get anything to work the way I need it to. If anyone has a way that can accomplish this, please let me know!

    Okay, so... OOP practices make me feel stupid sometimes. Heaven forbid I just create a Document and have it be a pointer to the JTextComponent's getDocument().
    /stupid

  • How to modify a string (bolt, underlined, font) inside the XML code

    Hi all, I have this code (used inside BI Publisher)
    <?if:INDUSTRY_COMPETENCE_DESCR != ''?> Industry competencies: <?for-each:G_IND_COMP?><?INDUSTRY_COMPETENCE_DESCR?><?end for-each?><?end if?>
    Anyone knows how can I show the string "Industry competencies" bold and underlined ? and also how can I set the format (font style, font dimensions, font colors, etc...) ?
    Regarding the bolt feature I tried the <B> from HTML but it doesn't work.....
    Any help will be appreciated
    Thanks
    Alex

    Hi all, I have this code (used inside BI Publisher)
    <?if:INDUSTRY_COMPETENCE_DESCR != ''?> Industry competencies: <?for-each:G_IND_COMP?><?INDUSTRY_COMPETENCE_DESCR?><?end for-each?><?end if?>
    Anyone knows how can I show the string "Industry competencies" bold and underlined ? and also how can I set the format (font style, font dimensions, font colors, etc...) ?
    Regarding the bolt feature I tried the <B> from HTML but it doesn't work.....
    Any help will be appreciated
    Thanks
    Alex

  • How do i get more accuracy in converting a string to decimal

    I am trying to read an attitude and heading referance sensor. An example of the data output is a string as follows;
    I -001.9 +00.0 006.8 +00.0
    I -001.9 -00.0 006.8 +00.0
    I -001.9 +00.0 006.8 +0 ... etc.
    It consists of various columns seperated by spaces. My problem is reading the digit after the decimal point. I have tried in two ways: first with the modified parse string example using the scan string vi and secondly with the spreadsheet string to array function. In both cases, the numbers are rounded of the the nearest integer and any negative signs are ignored. Can anyone suggest any reasons for this and/or how to get round it?
    Phil

    I have an example attached
    A multiline string splitted into an array of strings
    processed by scan from string in a for loop.
    If you look inside the for you find the solution for one line.
    I don't understand why you had the resolution problems but send me the original source and I can find out
    greetings from the Netherlands
    Attachments:
    scan_from_string_with_multiline.vi ‏41 KB

  • Passing (byref) String from Java to C++ via JNI

    I wish to pass a string to a C++ Dll as a parameter in a function. The problem is that I don't know howto receive back the data after it is filled in the C++ dll. I am trying to do what is called passing parameters by reference.
    Java Code:
    public class ABKeyBoard {
    public native long leerBanda(int pista, String datos);
    public static void main(String[] args) {
    String datos=new String();
    System.loadLibrary("ABKeyBoard");
    new ABKeyBoard().leerBanda(1,datos);
    System.out.println(datos); //the content of datos here is empty.
    C++ Code:
    Java_ABKeyBoard_leerBanda(JNIEnv *env, jobject obj,jint pista, jstring datos)
         char buffer[2024];
         memset(buffer,     0x00,     sizeof(buffer));
         strcpy(buffer, "xxxx");
         datos = env->NewStringUTF(buffer);
    return;
    Thanks for your help.

    In java every parameter are always passed by value.
    The datos parameter is a local copy of the string
    reference you pass to the method.This is wrong. The String passed to the native method is the same String object you use in Java. Although everything is passed by value in Java, what is actually passed by value is the reference to the String. This means that you can modify the object you pass, but you are not allowed to change the reference to point to a totally different object. That is where the problem is coming in.
    The trouble is that it is illegal to modify a String, even from native code. If you need to make changes in-place to the text, pass an array of chars (if your native code uses Unicode), an array of bytes (if it uses normal 8-bit characters) or a StringBuffer. You can legally modify any of these data structures with the new data. But the StringBuffer object is the only one whose length can be changed after it is created. Unfortunately it is also the hardest to use from JNI.
    Generally I think you should always pass arrays of bytes/chars to native code instead of Strings when possible. They can be modified in place, and you can use String's methods to get a byte-array in the platform's proper encoding. Using the GetStringUTFChars method is problematic because UTF only maps directly onto ASCII in the case of characters which are in the set of 7-bit ASCII characters. Your code will do wrong things if your String happens to contain some other character, unless your native code expects UTF format strings.
    The good news is that C(++) functions which return results in their arguments do not ordinarily change the length. So you should be able to allocate a byte[] or char[] ahead of time of the appropriate size (don't forget to add the trailing null, which is not a component of Java strings). I think byte[] or char[] is the best answer because you can easily map those onto C-style arrays with Get[Primitive]ArrayRegion; the return of that is suitable for passing directly to native code, as long as you have remembered the null-terminator. For instance you could do (*env)->GetByteArrayRegion(env, javaArray, 0, arrayLength, CArray) and then your CArray would be changed to point at the contents of the javaArray (note: it does not copy data into CArray, it changes CArray to point at the array contents, so do not allocate memory for CArray first). Then when you do ReleaseByteArrayRegion the results will be propagated back to Java.

  • String problem java.lang.NullPointerException

    Hii all :)
    How are u?? :)
    I have a little a problem with String object in this class (You can say its a homework ^__^ ).
    public class Personne {
         private String nom;
         private String prenom;
         private int age;
         public Personne(){
              this(null, null, 0);
         public Personne(String nom, String prenom, int age){
              setNom(nom);
              setPrenom(prenom);
              setAge(age);
         public void setNom(String nom){
              this.nom = new String(nom);
         public void setPrenom(String prenom){
              this.prenom = new String(prenom);
         public void setAge(int age){
              this.age = age;
         public String getNom(){
              return this.nom;
         public String getPrenom(){
              return this.prenom;
         public int getAge(){
              return this.age;
         public String toString(){
              System.out.print("Nom : " + this.getNom() + ", Penom : " + this.getPrenom() + ", Age : " + this.getAge() + " ");
              return null;
    }When i call the class personne with the Personne() i get these errors in compiling-time :
    Exception in thread "main" java.lang.NullPointerException
         at java.lang.String.<init>(Unknown Source)
         at Personne.setNom(Personne.java:18)
         at Personne.<init>(Personne.java:12)
         at Personne.<init>(Personne.java:8)
         at Main.main(Main.java:4) // The line wich i inisialize my object in my main method.
    can someone help me??
    Thank you alll ^__^
    Edited by: La VloZ on 18 mai 2013 22:50
    Edited by: La VloZ on 18 mai 2013 22:51
    Edited by: La VloZ on 18 mai 2013 22:51
    Edited by: La VloZ on 18 mai 2013 22:53
    Edited by: La VloZ on 18 mai 2013 22:55

    Why the error? Because you invoke the constructor String(String s), with s null. The constructor would produce a new String with the same character sequence as s, but if s is null, it cannot do this, so it throws NullPointerException. What else could it do? Without throwing an exception, a constructor has to create a new object, but there is no raw material, so to speak, for the creation. Think what would/could you do if you had to write such a 'copy constructor' for your own class and you would be passed null.
    Now, the String copy constructor is probably useless, as the javadoc hints. When you have a String already, you don't need to create an identical one, as the original will:
    - Not be garbage collected, if you keep a reference to it
    - Never be modified, as strings are immutable
    You are right that the code you show would 'copy the reference of nom to this.nom' and this is ok. It's exactly what you need, for the reasons above.

  • How do I modify multiple Menu rings in a loop?

    I would like to modify the Strings of 15 Menu Rings in a loop as follows:
    Calculate new values
    Start For Loop
    Write new values to property node Menu ring(N) / Strings[]
    End loop
    I want to have one poperty node in the loop, whos' reference (or link) gets modified, to point to a different Menu Ring for each iteration of the loop. In other words, without having 15 different property nodes.
    Is it possible?  
    Thanks.

    You can create a reference for each control (right click->create...), then build these references into an array using build array, then iterate over the array in a for loop using auto-indexing.
    You can do the same for the arrays of strings, but because the arrays can probably have different lengths, you should put each 1D array into a cluster and build a 1D array of the clusters. This is because a 2D array can not have a different number of elements in each row.
    If you do this kind of thing often, you can save time on creating the reference by using this.
    Try to take over the world!

  • Formatting a string

    Hello All
    Is there a way I can use format specifiers with variables?
    OK so I need to format a string to be a certain length equal to the longest string I am using. So what I would like to use is something like:
    %xs where x is the number of the length of the longest string I have. So if I have a string with 9 characters and one with 4 characters then I need 5 spaces on the left side of the 4 character string to push it to the right. (5 = 9 - 4). But the 9 might become 12 one time, or 3 the other, so it is a variable length.
    I tried to use concatenation to build the formatter expression, but the printf line did not understand it.
    Any help would be greatly appreciated.

    Well I can think of two solutions...
    If you want to not modify the Strings and just show the outcomes of adding the spaced you can simply print the appropriate amount of spaces before the string...
    public class Sandbox {
         public static void main(String[] arg)     {
              String s1 = new String("Hello World");
              String s2 = new String("Hello");
              System.out.println(s1);
              for (int x=0; x<(s1.length() - s2.length()); x++) {
                   System.out.print(" ");
              System.out.print(s2);
    OUTCOME:
    Hello World
          HelloBut if you want to actually make the string that certain amount of spaces longer you can use the following...
    import java.lang.StringBuilder;
    public class Sandbox2 {
         public static void main(String[] args) {
              String s1 = new String("Hello World");
              String s2 = new String("Hello");
              StringBuilder sb = new StringBuilder(s2);
              for (int x=0; x<(s1.length() - s2.length()); x++) {
                   sb.insert(0, " ");
              System.out.println(s1+"\n"+sb);
    OUTCOME:
    Hello World
          Hello

  • Removing characters from a String (concats, substrings, etc)

    This has got me pretty stumped.
    I'm creating a class which takes in a string and then returns the string without vowels and without even numbers. Vowels and even characters are considered "invalid." As an example:
    Input: "hello 123"
    Output: "hll 13"
    The output is the "valid" form of the string.
    Within my class, I have various methods set up, one of which determines if a particular character is "valid" or not, and it is working fine. My problem is that I can't figure out how to essentially "erase" the invalid characters from the string. I have been trying to work with substrings and the concat method, but I can't seem to get it to do what I want. I either get an OutOfBoundsException throw, or I get a cut-up string that just isn't quite right. One time I got the method to work with "hello" (it returned "hll") but when I modified the string the method stopped working again.
    Here's what I have at the moment. It doesn't work properly for all strings, but it should give you an idea of where i'm going with it.
    public String getValidString(){
              String valid = str;
              int start = 0;
              for(int i=0; i<=valid.length()-1; i++){
                   if(isValid(valid.charAt(i))==false){
                             String sub1 = valid.substring(start, i);
                             while(isValid(valid.charAt(i))==false)
                                  i++;
                             start=i;
                             String sub2 = valid.substring(i, valid.length()-1);
                             valid = sub1.concat(sub2);
              return valid;
         }So does anybody have any advice for me or know how I can get this to work?
    Thanks a lot.

    Thansk for the suggestions so far, but i'm not sure how to implement some of them into my program. I probably wasn't specific enough about what all I have.
    I have two classes. One is NoVowelNoEven which contains the code for handling the string. The other is simply a test class, which has my main() method, used for running the program.
    Here's my class and what's involved:
    public class NoVowelNoEven {
    //data fields
         private String str;
    //constructors
         NoVowelNoEven(){
              str="hello";
         NoVowelNoEven(String string){
              str=string;
    //methods
         public String getOriginal(){
              return str;
         public String getValidString(){
              String valid = str;
              int start = 0;
              for(int i=0; i<=valid.length()-1; i++){
                   if(isValid(valid.charAt(i))==false){
                             String sub1 = valid.substring(start, i);
                             while(isValid(valid.charAt(i))==false)
                                  i++;
                             start=i;
                             String sub2 = valid.substring(i, valid.length()-1);
                             valid = sub1.concat(sub2);
              return valid;
         public static int countValidChar(String string){
              int valid=string.length();
              for(int i=0; i<=string.length()-1; i++){
                   if(isNumber(string.charAt(i))==false){
                        if((upperVowel(string.charAt(i))==true)||lowerVowel(string.charAt(i))){
                             valid--;}
                   else if(even(string.charAt(i))==true)
                        valid--;
              return valid;
         private static boolean even(char num){
              boolean even=false;
              int test=(int)num-48;
              if(test%2==0)
                   even=true;
              return even;
         private static boolean isNumber(char chara){
              boolean number=false;
              for(int i=0; i<=9; i++){
                   if((int)chara-48==i){
                        number=true;
              return number;
         private static boolean isValid(char chara){
              boolean valid=true;
              if(isNumber(chara)==true){
                   if(even(chara)==true)
                        valid=false;
              if((upperVowel(chara)==true)||(lowerVowel(chara)==true))
                   valid=false;
              return valid;
    }So in my test class i'd have something like this:
    public class test {
    public static void main(String[] args){
         NoVowelNoEven test1 = new NoVowelNoEven();
         NoVowelNoEven test2 = new NoVowelNoEven("hello 123");
         System.out.println(test1.getOriginal());
         //This prints hello   (default constructor string is "hello")
         System.out.println(test1.countValidChar(test1.getOriginal()));
         //This prints 3
         System.out.println(test1.getValidString());
         //This SHOULD print hll
    }

  • Can we Edit #BOX_BODY# Substitution String?

    In apex 4.02 all templates #BOX_BODY# substitution string are used, I need to modified that string.
    Outer #BOX_BODY# if I add anything like Font size, table format and anyting html function not accepted that template string. Can any one help for this how to change that format?
    Thanks in Advance

    Sara254 wrote:
    In apex 4.02 all templates #BOX_BODY# substitution string are used, I need to modified that string.The <tt>#BOX_BODY#</tt> substitution string is replaced by the region content at display points
    Page Template Body (1. items below region content)
    Page Template Body (2. items below region content)
    Page Template Body (3. items above region content)
    and thus <tt>#BOX_BODY#</tt> can't be "modified". Make changes in the relevant regions.
    Outer #BOX_BODY# if I add anything like Font size, table format and anyting html function not accepted that template string. Can any one help for this how to change that format?HTML does not have "functions". It is a mark-up language for defining the structure of documents. Presentational elements like <tt>font</tt> have been deprecated for many years and are now removed from the language. <tt>table</tt> elements should be used to structure tabular data, not for page layout. Use CSS to control presentation.

  • String to XML including namspaces.

    How? I have this String "<foo:bar></foo:bar>". When try to parse it with Oracle Parser v2 it says
    oracle.xml.parser.v2.XMLParseException: Namespace prefix 'foo' used but not declared.Im not able to change the XML by adding somekind of xmlns:foo. Perhaps on runtime but not in the file.
    Thanks.

    Namespace prefixes must always be associated with a namespace in some way or other. For a namespace prefix to refer to a namespace it is required that there be a namespace declaration that declares the prefix to be related to the namespace. So there is no way to save using "somekind of xmlns:foo" but you can do this by modifying the string in the memory before parsing (a modified in-memory string would be passed to the parser) or even by making a copy of the original file the content of which could perhaps be modified.

Maybe you are looking for