gpt4 book ai didi

java - 检测字符串中的空格

转载 作者:行者123 更新时间:2023-12-01 16:32:35 25 4
gpt4 key购买 nike

如何判断用户输入的内容中是否有空格?用户的输入存储在字符串中。我所指的部分位于星号之间。我读到可以使用正则表达式,但我不知道如何使用它来检测字符串 s 中是否有空格。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class LAnalyze{

public static void main(String[] args) {

int j = 0;
String s = null;
Scanner scan = new Scanner(System.in);


System.out.println("Enter an input: ");
s = scan.nextLine();

****************************************************
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();

if(spaceIsFound)
*******************************************************
{
System.out.println("Invalid character(s) entered.. Program terminated!\n");
System.exit(0);
}
else if( s.charAt(0)=='a'||s.charAt(0)=='b'||s.charAt(0)=='c'||s.charAt(0)=='d'||s.charAt(0)=='e'||s.charAt(0)=='f'||
s.charAt(0)=='g'||s.charAt(0)=='h'||s.charAt(0)=='i'||s.charAt(0)=='j'||s.charAt(0)=='k'||s.charAt(0)=='l'||
s.charAt(0)=='m'||s.charAt(0)=='n'||s.charAt(0)=='o'||s.charAt(0)=='p'||s.charAt(0)=='q'||s.charAt(0)=='r'||
s.charAt(0)=='s'||s.charAt(0)=='t'||s.charAt(0)=='u'||s.charAt(0)=='v'||s.charAt(0)=='w'||s.charAt(0)=='x'||
s.charAt(0)=='y'||s.charAt(0)=='z'||s.charAt(0)=='A'||s.charAt(0)=='B'||s.charAt(0)=='C'||s.charAt(0)=='D'||
s.charAt(0)=='E'||s.charAt(0)=='F'||s.charAt(0)=='G'||s.charAt(0)=='H'||s.charAt(0)=='I'||s.charAt(0)=='J'||
s.charAt(0)=='K'||s.charAt(0)=='L'||s.charAt(0)=='M'||s.charAt(0)=='N'||s.charAt(0)=='O'||s.charAt(0)=='P'||
s.charAt(0)=='Q'||s.charAt(0)=='R'||s.charAt(0)=='S'||s.charAt(0)=='T'||s.charAt(0)=='U'||s.charAt(0)=='V'||
s.charAt(0)=='W'||s.charAt(0)=='X'||s.charAt(0)=='Y'||s.charAt(0)=='Z') {

System.out.print( (s) + ": Identifier\n");
for (int k = 0; k < s.length(); k++) {
j++;
System.out.println("Token " + (j) + " = " + (s.charAt(k)));

}
}
else if(s.charAt(0)=='0'||s.charAt(0)=='1'||s.charAt(0)=='2'||s.charAt(0)=='3'||s.charAt(0)=='4'||s.charAt(0)=='5'||
s.charAt(0)=='6'||s.charAt(0)=='7'||s.charAt(0)=='8'||s.charAt(0)=='9') {

System.out.print( (s) + ": Unsigned Integer\n");
for (int m = 0; m < s.length(); m++) {
j++;
System.out.println("Token " + (j) + " = " + (s.charAt(m)));
}
}
else {
System.out.println("Invalid character(s) entered.. Program terminated!\n");
System.exit(0);
}

}

}

最佳答案

可以使用 s.indexOf(' ');如果返回 -1,则字符串不包含空格。

此外,您还可以使用 开关(s.charAt(0)){ 情况“a”: 情况“b”: ... 休息; 案例“c”: ... }

代替多个if。

关于java - 检测字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13114331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com