' ' is space : true 删除开头的空白字符 Before stripLeading : ' Hello word java ' After stripLeading : 'Hello word java ' 删除结尾的空白字符 Before stripTrailing : ' Hello word java ' After stripTrailing : ' Hello word java'
public class StringTest {
public static void main(String args[]) {
String stringWithSpace =" Hello word java ";
StringTest.replaceAllTest(stringWithSpace," ");
StringTest.replaceAllTest(stringWithSpace,"\\s+");
StringTest.replaceAllTest(stringWithSpace,"^\\s+");
StringTest.replaceAllTest(stringWithSpace,"\\s+$");
}
private static void replaceAllTest(String stringWithSpace,String regex){
System.out.println("Before replaceAll with '"+ regex +"': \'" + stringWithSpace + "\'");
String stringAfterTrim = stringWithSpace.replaceAll(regex, "");
System.out.println("After replaceAll with '"+ regex +"': \'" + stringAfterTrim + "\'");
}
}
ログイン後にコピー
Before replaceAll with ' ': ' Hello word java ' After replaceAll with ' ': 'Hellowordjava' Before replaceAll with '\s+': ' Hello word java ' After replaceAll with '\s+': 'Hellowordjava' Before replaceAll with '^\s+': ' Hello word java ' After replaceAll with '^\s+': 'Hello word java ' Before replaceAll with '\s+$': ' Hello word java ' After replaceAll with '\s+$': ' Hello word java'
public class StringTest {
public static void main(String args[]) {
String stringWithSpace =" Hello word java ";
StringTest.replaceFirstTest(stringWithSpace," ");
StringTest.replaceFirstTest(stringWithSpace,"\\s+");
StringTest.replaceFirstTest(stringWithSpace,"^\\s+");
StringTest.replaceFirstTest(stringWithSpace,"\\s+$");
}
private static void replaceFirstTest(String stringWithSpace,String regex){
System.out.println("Before replaceFirst with '"+ regex +"': \'" + stringWithSpace + "\'");
String stringAfterTrim = stringWithSpace.replaceFirst(regex, "");
System.out.println("After replaceFirst with '"+ regex +"': \'" + stringAfterTrim + "\'");
}
}
ログイン後にコピー
结果:
Before replaceFirst with ' ': ' Hello word java ' After replaceFirst with ' ': ' Hello word java ' Before replaceFirst with '\s+': ' Hello word java ' After replaceFirst with '\s+': 'Hello word java ' Before replaceFirst with '^\s+': ' Hello word java ' After replaceFirst with '^\s+': 'Hello word java ' Before replaceFirst with '\s+$': ' Hello word java ' After replaceFirst with '\s+$': ' Hello word java'
以上がJavaで文字列からスペースを削除する方法は何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。