取出给定字符串的一部分并将获取的部分作为变量返回?

时间:2015-02-03 02:35:38

标签: java string if-statement

背景:Java中的极端初学者,所以我对字符串感到满意。我一直在寻找SO和Java API。

我的问题:我正在开发一个小型的聊天机器人项目。目标是当有人输入“我某事你”时,机器人应该返回“为什么你某事我?”随着某事成为任何事物,例如“爱”或说“我爱你”,让机器人回归“为什么你爱我?”

这个,希望也应该使用多个单词,所以如果有人写机器人“我实际上不喜欢你”机器人会回答“为什么你真的不喜欢我?”

为了做到这一点,我想砍掉“我”和“你”,留下什么,然后把它安排成一个新句子。我很熟悉,如果我知道字符串,我会怎​​么做,但是因为任何人都可以输入任何东西,作为初学者,我遇到了麻烦。这就是我得到的:

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 个答案:

答案 0 :(得分:0)

作为参考,Java有一个非常好的正则表达式匹配包:java.util.regex。这些类允许您测试字符串是否匹配&#34;我是&#34;然后,如果它匹配,则检索特定的命名&#34;组&#34;来自字符串。

例如:

Pattern pattern = Pattern.compile("I (.*) you");
Matcher matcher = pattern.matcher("I really dig you");
if (matcher.matches()) {
    System.out.println("Why do you " + matcher.group() + " me?");
}