宿題のこの部分は、文字列の集合を取ることを望んでおり、文字列のリストを返します。文字列セットには、電子メールアドレス、つまり[email protected]があります。私たちは電子メールアドレスの最初の部分を引っ張ります。その名前をString Listに入れます。上記の例では、mynameがListに追加されます。 私が現在持っているコードは、イテレータを使用して文字列をセットから取得します。次に、String.contains( "@")をエラーチェックとして使用して、文字列に@記号が含まれていることを確認します。次に、文字列の最後から文字列.charAt( "@")を使用して各文字をチェックします。それが見つかったら、正しい部分を含む部分文字列を作成してListに送ります。 私の問題は、何かを再帰的に使用して操作を減らそうとしていたことです。私はstring.length()/ 2を分割して、後半にString.contains( "@")を使用することを考えていました。その半分に@記号が含まれている場合、関数は再帰的にaginを呼び出します。後半に@記号が含まれていなかった場合、前半にはそれがあり、再帰的に関数を呼び出すことになります。文字の最適化を見つけよう
私の問題は、再帰的に関数を呼び出し、@記号が見つかると「部分文字列」を送信するときに、元の文字列のインデックスではなく部分文字列のインデックスのみを持つことになります。どのようにそれを追跡するための任意のアイデアや多分コマンド/私は見ている必要がありますメソッド。以下は私の元のコードです。アドバイスを歓迎します。
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