我想检索有人作为字符串输入的引号中的任何内容,我假设它是我需要的子字符串,但我不确定如何使用。
当用户输入由单词和数字混合而成的字符串时,它们之间用一个空格隔开:嘿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=""; } } } }
谢谢!
我不确定这是否正是您所需要的,但是它将逐步删除引用的部分…
String quote = "I say: \"I have something to say, \"It's better to burn out then fade away\"\" outloud..."; if (quote.contains("\"")) { while (quote.contains("\"")) { int startIndex = quote.indexOf("\""); int endIndex = quote.lastIndexOf("\""); quote = quote.substring(startIndex + 1, endIndex); System.out.println(quote); } }
哪个输出…
I have something to say, "It's better to burn out then fade away" It's better to burn out then fade away
更新
我不知道这是不是在欺骗…
String quote = "I say: \"I have something to say, \"It's better to burn out then fade away\"\" outloud...\"Just in case you don't believe me\""; String[] split = quote.split("\""); for (String value : split) { System.out.println(value); }
I say: I have something to say, It's better to burn out then fade away outloud... Just in case you don't believe me
好,假的 String#split
String#split
StringBuilder sb = new StringBuilder(quote.length()); for (int index = 0; index < quote.length(); index++) { if (quote.charAt(index) == '"') { System.out.println(sb); sb.delete(0, sb.length()); } else { sb.append(quote.charAt(index)); } }
好吧,这基本上是split带有选择的假货…
split
String quote = "blah blah 123 \"hello\" 234 \"world\""; boolean quoteOpen = false; StringBuilder sb = new StringBuilder(quote.length()); for (int index = 0; index < quote.length(); index++) { if (quote.charAt(index) == '"') { if (quoteOpen) { System.out.println("Quote: [" + sb.toString() + "]"); quoteOpen = false; sb.delete(0, sb.length()); } else { System.out.println("Text: [" + sb.toString() + "]"); sb.delete(0, sb.length()); quoteOpen = true; } } else { sb.append(quote.charAt(index)); } } if (sb.length() > 0) { if (quoteOpen) { System.out.println("Quote: [" + sb.toString() + "]"); } else { System.out.println("Text: [" + sb.toString() + "]"); } }
产生…
Text: [blah blah 123 ] Quote: [hello] Text: [ 234 ] Quote: [world]
知道,我不知道您如何存储结果。我很想创建一些能够存储String结果并将其添加到a的基本类,List以便我可以维持顺序,并可能使用某种类型的标志来确定它们是什么类型…
String
List