英文:
How do I remove all whitespaces from a string?
问题
I'm trying to remove all whitespaces from a string. I've googled a lot and found only replaceAll()
method is used to remove whitespace. However, in an assignment I'm doing for an online course, it says to use replace()
method to remove all whitespaces and to use \n
for newline character and \t
for tab characters. I tried it, here's my code:
public static String removeWhitespace(String s) {
String gtg = s.replace(' ', '');
gtg = s.replace('\t', '');
gtg = s.replace('\n', '');
return gtg;
}
After compiling, I get the error message:
Error:(12, 37) java: empty character literal
Error:(13, 37) java: empty character literal
Error:(14, 37) java: empty character literal
All 3 refer to the above replace()
code in public static String removeWhitespace(String s)
.
I'd be grateful if someone pointed out what I'm doing wrong.
英文:
I'm trying to remove all whitespaces from a string. I've googled a lot and found only replaceAll()
method is used to remove whitespace. However, in an assignment I'm doing for an online course, it says to use replace()
method to remove all whitespaces and to use \n
for newline character and \t
for tab characters. I tried it, here's my code:
public static String removeWhitespace(String s) {
String gtg = s.replace(' ', '');
gtg = s.replace('\t', '');
gtg = s.replace('\n', '');
return gtg;
}
After compiling, I get the error message:
Error:(12, 37) java: empty character literal
Error:(13, 37) java: empty character literal
Error:(14, 37) java: empty character literal
All 3 refer to the above replace()
code in public static String removeWhitespace(String s)
.
I'd be grateful if someone pointed out what I'm doing wrong.
答案1
得分: 3
有两种 replace()
的方法 - 一种接受字符,另一种接受字符串。你正在使用字符类型,这就是为什么你不能指定一个 "nothing" 字符。
使用字符串版本:
gtg = gtg.replace("\t", "");
还要注意我在那里纠正的错误:你的代码一遍又一遍地替换原始字符串中的字符,所以只有最后一次替换会生效。
你可以改成这样写:
public static String removeWhitespace(String s) {
return s.replaceAll("\\s", ""); // 使用正则表达式
}
英文:
There are two flavors of replace()
- one that takes chars and one that takes Strings. You are using the char type, and that's why you can't specify a "nothing" char.
Use the String verison:
gtg = gtg.replace("\t", "");
Notice also the bug I corrected there: your code replaces chars from the original string over and over, so only the last replace will be effected.
You could just code this instead:
public static String removeWhitespace(String s) {
return s.replaceAll("\\s", ""); // use regex
}
答案2
得分: 1
以下是您提供的代码的翻译部分:
尝试这段代码,
public class Main {
public static void main(String[] args) throws Exception {
String s = " Test example hello string replace enjoy hh ";
System.out.println("原始字符串 :"+s);
s = s.replace(" ", "");
System.out.println("没有空格的最终字符串 :"+s);
}
}
输出:
原始字符串 : Test example hello string replace enjoy hh
没有空格的最终字符串 :Testexamplehellostringreplaceenjoyhh
另一种方法是使用字符数组:
public class Main {
public static void main(String[] args) throws Exception {
String s = " Test example hello string replace enjoy hh ";
System.out.println("原始字符串 :"+s);
String ss = removeWhitespace(s);
System.out.println("没有空格的最终字符串 :"+ss);
}
public static String removeWhitespace(String s) {
char[] charArray = s.toCharArray();
String gtg = "";
for(int i =0; i<charArray.length; i++){
if ((charArray[i] != ' ') && (charArray[i] != '\t') &&(charArray[i] != '\n')) {
gtg = gtg + charArray[i];
}
}
return gtg;
}
}
输出:
原始字符串 : Test example hello string replace enjoy hh
没有空格的最终字符串 :Testexamplehellostringreplaceenjoyhh
英文:
Try this code,
public class Main {
public static void main(String[] args) throws Exception {
String s = " Test example hello string replace enjoy hh ";
System.out.println("Original String : "+s);
s = s.replace(" ", "");
System.out.println("Final String Without Spaces : "+s);
}
}
Output :
Original String : Test example hello string replace enjoy hh
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh
Another way by using char array :
public class Main {
public static void main(String[] args) throws Exception {
String s = " Test example hello string replace enjoy hh ";
System.out.println("Original String : "+s);
String ss = removeWhitespace(s);
System.out.println("Final String Without Spaces : "+ss);
}
public static String removeWhitespace(String s) {
char[] charArray = s.toCharArray();
String gtg = "";
for(int i =0; i<charArray.length; i++){
if ((charArray[i] != ' ') && (charArray[i] != '\t') &&(charArray[i] != '\n')) {
gtg = gtg + charArray[i];
}
}
return gtg;
}
}
Output :
Original String : Test example hello string replace enjoy hh
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh
答案3
得分: 0
如果您想为 replace(char,char)
方法指定一个空字符,应该这样做:
public static String removeWhitespace(String s) {
// 十进制格式或十六进制格式
return s.replace(' ', (char) 0)
.replace('\f', (char) 0)
.replace('\n', (char) 0)
.replace('\r', '\u0000')
.replace('\t', '\u0000');
}
但空字符仍然是一个字符,因此最好为 replace(CharSequence,CharSequence)
方法指定一个空字符串来删除这些字符:
public static String removeWhitespace(String s) {
return s.replace(" ", "")
.replace("\f", "")
.replace("\n", "")
.replace("\r", "")
.replace("\t", "");
}
为了简化这段代码,您可以为 replaceAll(String,String)
方法指定一个正则表达式来删除所有空白字符:
public static String removeWhitespace(String s) {
return s.replaceAll("\\s", "");
}
英文:
If you want to specify an empty character for the replace(char,char)
method, you should do it like this:
public static String removeWhitespace(String s) {
// decimal format, or hexadecimal format
return s.replace(' ', (char) 0)
.replace('\f', (char) 0)
.replace('\n', (char) 0)
.replace('\r', '\u0000')
.replace('\t', '\u0000');
}
But an empty character is still a character, therefore it is better to specify an empty string for the replace(CharSequence,CharSequence)
method to remove those characters:
public static String removeWhitespace(String s) {
return s.replace(" ", "")
.replace("\f", "")
.replace("\n", "")
.replace("\r", "")
.replace("\t", "");
}
To simplify this code, you can specify a regular expression for the replaceAll(String,String)
method to remove all whitespace characters:
public static String removeWhitespace(String s) {
return s.replaceAll("\\s", "");
}
<sup>See also:
<br>• Replacing special characters from a string
<br>• First unique character in a string using LinkedHashMap</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论