gpt4 book ai didi

java - 如何获取用户输入的字符串中 ""之间的内容? java

转载 作者:行者123 更新时间:2023-12-02 06:45:47 24 4
gpt4 key购买 nike

我想检索某人作为字符串输入的引号中的任何内容,我假设它是我需要的子字符串,但我不确定如何。

当用户输入一个由单词和数字混合而成的字符串并用一个空格分隔时: 嘿 110 说“我不太擅长 Java”但是“我钓鱼很好”

然后我希望能够获取“我不太擅长 Java”和“我可以很好地钓鱼”并打印出引号内的内容,以便字符串中可以有多个引号。现在我有 if( userInput=='"') 然后我用子字符串做一些事情,但我不确定什么。

不幸的是,我不能使用 split、trim、tokenizer、regex 或任何能让这变得非常简单的东西。

这一切都在这个方法中,我尝试识别字符串中的内容是否是单词、数字或引号:

public void set(String userInput)// method set returns void
{
num=0;// reset each variable so new input can be passed

String empty="";
String wordBuilder="";
userInput+=" ";
for(int index=0; index<userInput.length(); index++)// goes through each character in string
{

if(Character.isDigit(userInput.charAt(index)))// checks if character in the string is a digit
{

empty+=userInput.charAt(index);



}
else
{
if (Character.isLetter(userInput.charAt(index)))
{

wordBuilder+=userInput.charAt(index);

}
else
{
if(userInput.charAt(index)=='"')
{
String quote=(userInput.substring(index,);

}
}
//if it is then parse that character into an integer and assign it to num
num=Integer.parseInt(empty);
word=wordBuilder;


empty="";
wordBuilder="";
}


}

}


}

谢谢!

最佳答案

尝试下一个:

public static void main(String[] args) {
String input = "\"123\" hey 110 say \"I am not very good at Java\" but \" I can fish pretty well\"";
int indexQuote = -1;
boolean number = true;
String data = "";
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isWhitespace(ch)) {
if (data.length() > 0 && indexQuote == -1) {
if (number) {
System.out.println("It's a number: " + data);
} else {
System.out.println("It's a word: " + data);
}
// reset vars
number = true;
data = "";
} else if (indexQuote != -1) {
data += ch;
}
} else if (ch == '"') {
if (indexQuote == -1) {
number = false;
indexQuote = i;
} else {
System.out.println("It's a quote: " + data);
// reset vars
number = true;
data = "";
indexQuote = -1;
}
} else {
if (!Character.isDigit(ch)) {
number = false;
}
data += ch;
if (data.length() > 0 && i == input.length() - 1) {
if (number) {
System.out.println("It's a number: " + data);
} else {
System.out.println("It's a word: " + data);
}
}
}
}
}

输出:

It's a word: hey
It's a number: 110
It's a word: say
It's a quote: I am not very good at Java
It's a word: but
It's a quote: I can fish pretty well

关于java - 如何获取用户输入的字符串中 ""之间的内容? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18649204/

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