Results 1 to 4 of 4

Thread: Converting String to String Array and vice-versa [Java]

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Posts
    308

    Question Converting String to String Array and vice-versa [Java]

    Coding Style: NetBeans IDE 4.0 Beta2 [Java]

    Given a string [strFormat] I need to convert it (using predefined delimiters {}) into a string array. And then I must be able to go the other way (convert the string array back into a string with delimiters {})

    So for example:
    Given a string strFormat = "{Hello}{Bye}{Ouch}"
    I need to put this in a string array [strFormatArray] so that strFormatArray[0] = "Hello", strFormatArray[1] = "Bye", strFormatArray[2] = "Ouch"
    Then later I need to be able to take the string array [strFormatArray] and convert it back to the original string [strFormat] with the delimiters.

    Any easy way to accomplish this? [built in string and conversion functions]?
    Any ideas?

  2. #2
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,190

    Re: Converting String to String Array and vice-versa [Java]

    I guess you can use:


    int indexOf("String")


    to find out where the first "{" is, then use it again to find out where the first "}" is.

    Then use:

    String substring(iStart, iEnd)


    to take out what is in the middle


    Then you have to choose your self if you just want to remember where you ended and next time use:

    int indexOf("String", iStartToRead)

    to read the rest, or if you want to make a new string with the rest of the string and read it from there.




    ØØ

  3. #3
    Registered User
    Join Date
    Jul 2014
    Posts
    2

    Re: Converting String to String Array and vice-versa [Java]

    You can make use of regular expression when splitting the string. You String split method.

    Example

    String delimiters = "{|{}";
    String strFormat = "{Hello}{Bye}{Ouch}"

    // analyzing the string
    String[] tokensVal = strFormat .split(delimiters);

  4. #4
    Addicted Member
    Join Date
    Oct 2008
    Location
    Califorina
    Posts
    235

    Re: Converting String to String Array and vice-versa [Java]

    Or something like this.

    Code:
    		String myString = "{Hello}{Bye}{Ouch}";
    		
    		myString = myString.replace("{", "");
    		
    		String[] myStringArray = myString.split("}");
    		
    		System.out.println(myString);
    		System.out.println(myStringArray[0]);
    		
    		for (int x = 0; x < myStringArray.length; x++) {
    			System.out.print("{" + myStringArray[x] + "}");
    		}

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width