问题
I have a programming homework. It says that I need to reverse the string first, then change it to uppercase and then remove all the whitespaces. I actually did it, but our professor didn't say anything about using replaceAll()
method. Is there any other way to do it beside replaceAll()
?
Here is my code:
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
System.out.println(reverse.toUpperCase().replaceAll("\\s", ""));
}
回答1:
You can check each character in turn using Character.isWhitespace
. Additionally, it is generally better to use a StringBuilder
when concatenating inside a loop.
public static void main(String[] args) {
String line = "the quick brown fox";
StringBuilder sb = new StringBuilder(line.length());
for (int i = line.length() - 1; i >= 0; i--) {
char c = line.charAt(i);
if(!Character.isWhitespace(c)) sb.append(Character.toUpperCase(c));
}
System.out.println(sb);
}
回答2:
@Khelwood's answer as code:
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
char currentChar = line.charAt(i);
if (currentChar != ' ') {
reverse += currentChar;
}
}
System.out.println(reverse.toUpperCase());
}
回答3:
Even without using replaceAll(), it’s still a one-liner:
String reverse = new StringBuilder(line).reverse().toString().toUpperCase().replace(" ", "");
回答4:
Character#isWhitespace
Initialize a StringBuilder
object and iterate through each character of the uppercased string. While iterating, use Character#isWhitespace
to check if the character is a whitespace character. If not, append the character to the StringBuilder
object. After the loop is finished, the StringBuilder
object will have all characters except the whitespace characters.
public class Main {
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
String upperCased = reverse.toUpperCase();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < upperCased.length(); i++) {
char ch = upperCased.charAt(i);
if (!Character.isWhitespace(ch)) {
sb.append(ch);
}
}
System.out.println("The given string: " + line);
System.out.println("The reverse of the given string: " + reverse);
System.out.println("The reverse of the given string in UPPER case: " + upperCased);
System.out.println("After removing all space from the reverse of the given string in UPPER case: " + sb);
}
}
Output:
The given string: the quick brown fox
The reverse of the given string: xof nworb kciuq eht
The reverse of the given string in UPPER case: XOF NWORB KCIUQ EHT
After removing all space from the reverse of the given string in UPPER case: XOFNWORBKCIUQEHT
Note:
- If you want to convert
sb
to aString
, usesb.toString()
. - You can use
String
instead ofStringBuilder
but I recommend you useStringBuilder
instead ofString
for such a case because repeated string concatenation in a loop creates additional as many instances ofString
as the number of concatenation. Check this discussion to learn more about it.
回答5:
You can use String.codePoints method to iterate over int
values of the characters of this string, to reverse their order, change to uppercase and remove whitespaces:
String line = "the quick brown fox";
String reverse = line
// return IntStream
.codePoints()
// return Stream<Character>
.mapToObj(ch -> (char) ch)
// reverse the order
// of characters once
.sorted((ch1, ch2) -> -1)
// change to uppercase
.map(Character::toUpperCase)
// remove whitespaces
.filter(ch -> !Character.isWhitespace(ch))
// return Stream<String>
.map(String::valueOf)
// join strings with
// characters back
// to a single string
.collect(Collectors.joining());
System.out.println(reverse); // XOFNWORBKCIUQEHT
See also: Is there a way to reverse specific arrays in a multidimensional array?
回答6:
to strictly follow the professors description (and intentions?):
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
String upperCase = reverse.toUpperCase();
String noSpaces = "";
for (int i = 0; i < upperCase.length(); i++) {
char ch = upperCase.charAt(i);
if (!Character.isWhitespace(ch)) {
noSpaces = noSpaces + ch; // or noSpaces += ch;
}
}
System.out.println(noSpaces);
}
Note 1: this can all be done with one loop, but that would not match the description (or no (user)loop at all?).
Note 2: the use of StringBuilder
is not needed anymore (when using an actual Java version (>= 11)) - actually I believe it is more efficient not to use it, the compiler does better job (see StringConcatFactory
)
Note 3: if allowed to use StringBuilder
, it also has a reverse
method
Note 4: be aware (for future) that replaceAll()
works with regular expression, very powerful, but kind of overkill to just replace a char - replace()
would be more moderate
回答7:
Here are two ways. The first uses a standard loop.
String line = "the quick brown fox";
StringBuilder sb = new StringBuilder();
for (int i = line.length() - 1; i >= 0; i--) {
char ch;
if ((ch = line.charAt(i)) != ' ') {
sb.append(Character.toUpperCase(ch));
}
}
System.out.println(sb.toString());
Prints
XOFNWORBKCIUQEHT
The second makes use of StringBuilder
and replaceAll
. And regardless, you should ask your professor since nothing was overtly forbidden.
String str = new StringBuilder("the quick brown fox")
.reverse().toString().replaceAll("\\s+", "").toUpperCase();
System.out.println(str);
Also prints
XOFNWORBKCIUQEHT
回答8:
If you do not need to store the reversed line, you can also just iterate it backwards and print the character immediately.
public static void main(String[] args) {
String line = "the quick brown fox";
for (char c : line.toUpperCase().toCharArray()) {
if (!Character.isWhitespace(c)) {
System.out.print(c);
}
}
}
来源:https://stackoverflow.com/questions/65374534/is-there-any-other-way-to-remove-all-whitespaces-in-a-string