![](/img/trans.png)
[英]java - check whether a string contains any characters other than spaces
[英]How do I check whether input string contains any spaces?
我有一個要求輸入 XML 元素名稱的輸入對話框,我想檢查它是否有空格。
我可以做一些類似 name.matches() 的事情嗎?
為什么要使用正則表達式?
name.contains(" ")
這應該也能正常工作,而且速度更快。
如果您將使用 Regex,它已經為任何非空白字符提供了一個預定義的字符類“\\S”。
!str.matches("\\S+")
告訴您這是否是至少一個字符的字符串,其中所有字符都是非空格
一個簡單的答案,與之前的答案類似:
str.matches(".*\\s.*")
當您將所有這些放在一起時,如果字符串中的任何位置有一個或多個空格字符,則返回 true。
這是一個簡單的測試,您可以運行它來對您的解決方案進行基准測試:
boolean containsWhitespace(String str){
return str.matches(".*\\s.*");
}
String[] testStrings = {"test", " test", "te st", "test ", "te st",
" t e s t ", " ", "", "\ttest"};
for (String eachString : testStrings) {
System.out.println( "Does \"" + eachString + "\" contain whitespace? " +
containsWhitespace(eachString));
}
string name = "Paul Creasey";
if (name.contains(" ")) {
}
如果你真的想要一個正則表達式,你可以使用這個:
str.matches(".*([ \t]).*")
從某種意義上說,與此正則表達式匹配的所有內容都不是有效的 xml 標記名稱:
if(str.matches(".*([ \t]).*"))
print "the input string is not valid"
if (str.indexOf(' ') >= 0)
會(稍微)更快。
這已在 android 7.0 到 android 10.0 中進行了測試,並且可以正常工作
使用這些代碼檢查字符串是否包含空格/空格可能位於第一個位置、中間位置或最后一個位置:
name = firstname.getText().toString(); //name is the variable that holds the string value
Pattern space = Pattern.compile("\\s+");
Matcher matcherSpace = space.matcher(name);
boolean containsSpace = matcherSpace.find();
if(constainsSpace == true){
//string contains space
}
else{
//string does not contain any space
}
您可以使用此代碼檢查輸入字符串是否包含任何空格?
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the string...");
String s1=sc.nextLine();
int l=s1.length();
int count=0;
for(int i=0;i<l;i++)
{
char c=s1.charAt(i);
if(c==' ')
{
System.out.println("spaces are in the position of "+i);
System.out.println(count++);
}
else
{
System.out.println("no spaces are there");
}
}
要檢查字符串是否不包含任何空格,您可以使用
string.matches("^\\S*$")
例子:
"name" -> true
" " -> false
"name xxname" -> false
您可以使用正則表達式“\\\\s”
計算空格數的示例程序(Java 9 及更高版本)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\s", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("stackoverflow is a good place to get all my answers");
long matchCount = matcher.results().count();
if(matchCount > 0)
System.out.println("Match found " + matchCount + " times.");
else
System.out.println("Match not found");
}
}
對於Java 8 及以下版本,您可以在 while 循環中使用 matcher.find() 並增加計數。 例如,
int count = 0;
while (matcher.find()) {
count ++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.