This site requires JavaScript, please enable it in your browser!
Greenfoot back
erdelf
erdelf wrote ...

2012/11/26

java alternative to string.copy?

erdelf erdelf

2012/11/26

#
Is there a java method for the c++ method string.copy?
davmac davmac

2012/11/26

#
Strings are immutable in Java, so copying them is pointless. Or am I not understanding your question?
erdelf erdelf

2012/11/26

#
the copy method in c++ is made for copying only parts between two chars in a string
davmac davmac

2012/11/26

#
Use the "substring" method. All the String methods are documented: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
erdelf erdelf

2012/11/26

#
definition of String.copy are you sure that substring would be the same?
www.cplusplus.com wrote...
str.copy(s,n,pos); s Array where the sequence of characters is copied. The storage space of the array shall already be allocated and should be large enough to contain n characters. n Number of characters to be copied. If this number is greater than the amount of characters between pos and the end of the string content, only those characters between pos and the end of the string are copied. pos Position of the first character to be copied from the string. out_of_range is thrown if pos>size().
davmac davmac

2012/11/27

#
It's not exactly the same, but it gives you part of the string, which is essentially what string::copy does. If you were more specific on how you wanted to use it / what you need it for, then I could give you more detail.
erdelf erdelf

2012/11/27

#
I am trying to convert some c++ code to java, and I am almost done, except the string.copy. Here is the usage in c++:
int i = str.copy(str2, int2 - int3 - 3, int4 + 3);
alainmoran alainmoran

2012/11/27

#
Native classes are usually passed by value, however if you really need to duplicate the data then you can use the following: String myString = new String(sourceString);
davmac davmac

2012/11/27

#
Right, so you want to copy the string from position 'int4 + 3' and size 'int2 - int3 - 3': str2 = str.substring(int4 + 3, int4 + int2 + int3); Or, if you need to preserve the trailing part of str2, you could do: str2 = str.substring(int4 + 3, int4 + int2 + int3) + str2.substring(int2 - int3 - 3);
erdelf erdelf

2012/11/27

#
in the c++ code it says int1 = ...
davmac davmac

2012/11/27

#
Well apparently, the C++ copy method returns: The effective length of the sequence of characters copied to s. This may either be equal to parameter n or to size()-pos, whichever is smaller (see description of parameter n). which also makes me notice that the code I gave above doesn't account for when the specified substring would be longer than the string itself. But you can check that for yourself, adjust the second parameter of substr appropriately, and calculate the amount "copied" by subtracting the first parameter value from the second (or even just taking the length of the substring).
You need to login to post a reply.