因此,这部分作业要求我们采用一组字符串,然后我们将返回一个字符串列表。在字符串集中,我们将有电子邮件地址,即[email protected]。我们要拉第一部分的电子邮件地址;该名称并将其放入字符串列表中。从上面的示例myname将被放入列表中。 我目前使用的代码使用迭代器从Set中提取字符串。然后,我使用String.contains(“@”)作为错误检查,以确保String中包含@符号。然后我从字符串的末尾开始,并使用string.charAt(“@”)来检查每个字符。一旦找到我,然后用正确的部分创建一个子字符串并将其发送到列表。 我的问题是我想使用递归和减少操作。我想到的东西会分割string.length()/ 2,然后在下半部分首先使用String.contains(“@”)。如果那一半包含@符号,那么它会递归地调用函数。如果后半部分不包含@符号,则前半部分将包含它,我们将调用函数递归发送它。查找字符优化
所以我的问题是,当我递归地调用函数并发送它的“子字符串”,一旦我找到@符号,我将只有子字符串的索引,而不是原始字符串的索引。关于如何跟踪它的任何想法或者我应该关注的命令/方法。以下是我的原始代码。欢迎任何建议。
public static List<String> parseEmail(Set<String> emails)
{
List<String> _names = new LinkedList<String>();
Iterator<String> eMailIt=emails.iterator();
while(eMailIt.hasNext())
{
String address=new String(eMailIt.next());
boolean check=true;
if(address.contains("@"))//if else will catch addresses that do not contain '@' .
{
String _address="";
for(int i=address.length(); i>0 && check; i--)
{
if('@'==address.charAt(i-1))
{
_address=new String(address.substring(0,i-1));
check=false;
}
}
_names.add(_address);
//System.out.println(_address);//fill in with correct sub string
}
else
{
//System.out.println("Invalid address");
_names.add("Invalid address");//This is whats shownn when you have an address that does not have an @ in it.
} // could have it insert some other char i.e. *%# s.t. if you use the returned list it can skip over invalid emails
}
return _names;
}
**有人建议我用String.indexOf(“@”),但根据API此方法只还给符号的第一次出现,我必须假设的工作,有可能在地址中是多个“@”,我必须使用最后一个。不过谢谢你的建议。我正在看另一个建议,并会回报。
***所以有一个string.lastindexOf(),这就是我所需要的。
public static List<String> parseEmail(Set<String> emails)
{
List<String> _names = new LinkedList<String>();
Iterator<String> eMailIt=emails.iterator();
while(eMailIt.hasNext())
{
String address=new String(eMailIt.next());
if(address.contains("@"))//if else will catch addresses that do not contain '@' .
{
int endex=address.lastIndexOf('@');
_names.add(address.substring(0,endex-1));
// System.out.println(address.substring(0,endex));
}
else
{
// System.out.println("Invalid address");
_names.add("Invalid address");//This is whats shownn when you have an address that does not have an @ in it.
} // could have it insert some other char i.e. *%# s.t. if you use the returned list it can skip over invalid emails
}
return _names;
}
'eMailIt.next()'和'address.substring(0,i-1)'都返回一个String,并且不需要在代码中调用'new'运算符。 – Gevorg 2012-02-11 19:08:08