vovastyle.blogg.se

Java string replaceall
Java string replaceall








java string replaceall

You almost always want to use Objects.equals(). Objects.equals("test", new String("test")) // -> true but you should really just call Objects.equals() string literals are concatenated by the compiler the compiler and thus refer to the same object but these are because literals are interned by New String("test") = new String("test") // -> false New String("test").equals("test") // -> true equals() so you don't have to (available as of JDK7, also available in Guava).Ĭonsequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals(). Objects.equals() checks for null before calling. equals() tests for value equality (whether they are logically "equal"). = tests for reference equality (whether they are the same object). If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters. It will be encoded and decoded just the same, because you are just looking at the bytes. (bytes, 0, chars, 0, bytes.Length) Īs long as your program (or other programs) don't try to interpret the bytes somehow, which you obviously didn't mention you intend to do, then there is nothing wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.Īdditional benefit to this approach: It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway! Do NOT use on arbitrary bytes only use on GetBytes's output on the SAME systemĬhar chars = new char (str.ToCharArray(), 0, bytes, 0, bytes.Length) Just do this instead: static byte GetBytes(string str)īyte bytes = new byte You certainly do NOT need to worry about encodings for this. (And, of course, to be able to re-construct the string from the bytes.)įor those goals, I honestly do not understand why people keep telling you that you need the encodings. Like you mentioned, your goal is, simply, to "get what bytes the string has been stored in". Contrary to the answers here, you DON'T need to worry about encoding if the bytes don't need to be interpreted!










Java string replaceall