我有一个这样的字符串:
mysz = "name=john age=13 year=2001";
我想删除字符串中的空格。我尝试了trim(),但这只删除了整个字符串前后的空格。我还尝试了replaceAll(“\\W”,“”),但随后=也被删除。
如何通过以下方式实现字符串:
mysz2 = "name=johnage=13year=2001"
我有一个这样的字符串:
mysz = "name=john age=13 year=2001";
我想删除字符串中的空格。我尝试了trim(),但这只删除了整个字符串前后的空格。我还尝试了replaceAll(“\\W”,“”),但随后=也被删除。
如何通过以下方式实现字符串:
mysz2 = "name=johnage=13year=2001"
当前回答
您还可以查看下面的Java代码。以下代码不使用任何“内置”方法。
/**
* Remove all characters from an alphanumeric string.
*/
public class RemoveCharFromAlphanumerics {
public static void main(String[] args) {
String inp = "01239Debashish123Pattn456aik";
char[] out = inp.toCharArray();
int totint=0;
for (int i = 0; i < out.length; i++) {
System.out.println(out[i] + " : " + (int) out[i]);
if ((int) out[i] >= 65 && (int) out[i] <= 122) {
out[i] = ' ';
}
else {
totint+=1;
}
}
System.out.println(String.valueOf(out));
System.out.println(String.valueOf("Length: "+ out.length));
for (int c=0; c<out.length; c++){
System.out.println(out[c] + " : " + (int) out[c]);
if ( (int) out[c] == 32) {
System.out.println("Its Blank");
out[c] = '\'';
}
}
System.out.println(String.valueOf(out));
System.out.println("**********");
System.out.println("**********");
char[] whitespace = new char[totint];
int t=0;
for (int d=0; d< out.length; d++) {
int fst =32;
if ((int) out[d] >= 48 && (int) out[d] <=57 ) {
System.out.println(out[d]);
whitespace[t]= out[d];
t+=1;
}
}
System.out.println("**********");
System.out.println("**********");
System.out.println("The String is: " + String.valueOf(whitespace));
}
}
输入:
String inp = "01239Debashish123Pattn456aik";
输出:
The String is: 01239123456
其他回答
import java.util.*;
public class RemoveSpace {
public static void main(String[] args) {
String mysz = "name=john age=13 year=2001";
Scanner scan = new Scanner(mysz);
String result = "";
while(scan.hasNext()) {
result += scan.next();
}
System.out.println(result);
}
}
\W表示“非文字字符”。空白字符的模式为%s。这在Pattern javadoc中有很好的记录。
String a="string with multi spaces ";
//or this
String b= a.replaceAll("\\s+"," ");
String c= a.replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ");
//任何空间都可以使用*别忘了sting b中的空格
可以使用isWhitespace函数从字符类中删除空白。
public static void main(String[] args) {
String withSpace = "Remove white space from line";
StringBuilder removeSpace = new StringBuilder();
for (int i = 0; i<withSpace.length();i++){
if(!Character.isWhitespace(withSpace.charAt(i))){
removeSpace=removeSpace.append(withSpace.charAt(i));
}
}
System.out.println(removeSpace);
}
public String removeSpaces(String word){
StringBuffer buffer = new StringBuffer();
if(word != null){
char[] arr = word.toCharArray();
for(int i=0; i < arr.length; i++){
if(!Character.isSpaceChar(arr[i])) {
buffer.append(arr[i]);
}
}
}
return buffer.toString();
}