Package java.lang.*
String
The String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
StringBuffer
A thread-safe, mutable sequence of characters. A string buffer is like a String
, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.
StringBuilder
A mutable sequence of characters. This class provides an API compatible with StringBuffer
, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer
in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer
as it will be faster under most implementations.
Example:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
1. String Nested Function:
public class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replace(" ", "%20");
}
}
2. create a new string
public class Solution {
public String replaceSpace(StringBuffer str) {
StringBuilder strb = new StringBuilder();
for(int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if(c == ' ')
{
strb.append("%20");
}
else
strb.append(c);
}
return strb.toString();
}
}
3.firstly calculate the number of all spaces of the string then resize it and set char value
public class Solution {
public String replaceSpace(StringBuffer str) {
int spacenum = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ' '){
spacenum++;
}
}
int oldLength = str.length();
int oldIndex = oldLength - 1;
int newLength = oldLength + spacenum*2;
str.setLength(newLength);
int newIndex = newLength - 1;
for(; oldIndex >= 0 && oldLength < newLength; oldIndex--){
if(str.charAt(oldIndex) == ' '){
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--, '2');
str.setCharAt(newIndex--, '%');
}else{
str.setCharAt(newIndex--, str.charAt(oldIndex));
}
}
return str.toString();
}
}
C++
class Solution {
public:
void replaceSpace(char *str,int length) {
for(int i = length - 1; i >= 0; i--)
{
if(str[i] == ' ')
{
for(int j = length - 1; j > i; j--)
{
str[j+2] = str[j];
}
str[i] = '%';
str[i+1] = '2';
str[i+2] = '0';
}
}
}
};