Fastest way to put contents of Set to a single String with words separated by a whitespace?

With commons/lang you can do this using StringUtils.join: You can’t really beat that for brevity. Update: Re-reading this answer, I would prefer the other answer regarding Guava’s Joiner now. In fact, these days I don’t go near apache commons. Another Update: Java 8 introduced the method String.join() While this isn’t as flexible as the Guava version, it’s handy when … Read more

How do you allow spaces to be entered using scanf?

People (and especially beginners) should never use scanf(“%s”) or gets() or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then). Remember than scanf stands for “scan formatted” and there’s precious little less formatted than user-entered data. It’s ideal if you have total control of … Read more

Remove spaces from std::string in C++

The best thing to do is to use the algorithm remove_if and isspace: Now the algorithm itself can’t change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container: We … Read more

Remove spaces from std::string in C++

The best thing to do is to use the algorithm remove_if and isspace: Now the algorithm itself can’t change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container: We … Read more

Removing whitespace from strings in Java

st.replaceAll(“\\s+”,””) removes all whitespaces and non-visible characters (e.g., tab, \n). st.replaceAll(“\\s+”,””) and st.replaceAll(“\\s”,””) produce the same result. The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one. Assign the value to a variable, if not used directly: