java取出给定字符串的一部分,并将所取部分作为变量返回?
背景:Java的极端初学者,所以我刚刚开始熟悉字符串。我一直在到处寻找SO和JavaAPI
我的问题是:我正在做一个聊天机器人项目。目标是当有人输入“Isomethingyou”时,机器人应该返回“Why do yousomethingme?”用某物做任何事,例如“爱”或说“我爱你”,然后机器人返回“你为什么爱我?”
这,希望也应该与多个词一起工作,所以如果有人给机器人写“我真的不喜欢你”,机器人会回答“你为什么真的不喜欢我?”
为了做到这一点,我想把“我”和“你”去掉,把剩下的部分,整理成一个新句子。我很熟悉,如果我知道字符串,我会怎么做,但由于任何人都可以输入任何东西,作为一个初学者,我遇到了麻烦。以下是我得到的:
public String getResponse(String statement)
{
String response = "";
if (findKeyword(statement, "I") >= 0
|| findKeyword(statement, "you") >= 0)
{
response = transformWhyDoYouStatement(statement);
}
return response;
}
private String transformWhyDoYouStatement(String statement)
{
// Remove the final period, if there is one
statement = statement.trim();
String lastChar = statement.substring(statement
.length() - 1);
if (lastChar.equals("."))
{
statement = statement.substring(0, statement
.length() - 1);
}
//String[] parts = string.split(" ");
len = statement.length;
String restOfStatement = statement.substring(psnOfYou + 3, psnOfMe).trim();
return "Why do you" + restOfStatement + " me?";
}
private int findKeyword(String statement, String goal, int startPos)
{
String phrase = statement.trim();
// The only change to incorporate the startPos is in the line below
int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(), startPos);
// Refinement--make sure the goal isn't part of a word
while (psn >= 0)
{
// Find the string of length 1 before and after the word
String before = " ", after = " ";
if (psn > 0)
{
before = phrase.substring (psn - 1, psn).toLowerCase();
}
if (psn + goal.length() < phrase.length())
{
after = phrase.substring(psn + goal.length(), psn + goal.length() + 1).toLowerCase();
}
// If before and after aren't letters, we've found the word
if (((before.compareTo ("a") < 0 ) || (before.compareTo("z") > 0)) // before is not a letter
&& ((after.compareTo ("a") < 0 ) || (after.compareTo("z") > 0)))
{
return psn;
}
// The last position didn't work, so let's find the next, if there is one.
psn = phrase.indexOf(goal.toLowerCase(), psn + 1);
}
return -1;
}
# 1 楼答案
作为参考,Java有一个非常好的正则表达式匹配包:
java.util.regex
。这些类允许您测试字符串是否匹配“I you”这样的模式,如果匹配,则从字符串中检索特定的命名“组”例如: