好吧,所以我有这个功能,该功能应该返回带有某些字符的字符串
String x = "DannyKrosis@Gmail.com";
private String Algorithm() {
for (int a = 0; a < x.length(); a++)
{
switch (x.charAt(a)) { // Goes over each character until the '@' character is found
case '@':
x = x.replace(x.charAt(a), ' '); // Replaces the '@' character with blank space
for (int b = a; b >= 0; b--) // From where the '@' was, replaces all characters before it
{
x = x.replace(x.charAt(b), ' ');
}
break;
}
}
return x.replaceAll("\s+", ""); // Removes all spaces to make string clean :)
}
当此功能返回字符串时,我得到
"Gml.cm"
当我希望它为
时"Gmail.com"
所以我尝试了此功能,希望得到我所需的结果
String x = "DannyKrosis@Gmail.com";
private String Algorithm() {
boolean y = false;
for (int a = 0; a < x.length(); a++)
{
switch (x.charAt(a)) {
case '@':
x = x.replace(x.charAt(a), ' '); // Removes '@' symbol from string
x = x.replaceAll("\s+", ""); // Removes all excess spaces
y = true; // Stops for loop
break;
default:
x = x.replace(x.charAt(a), ' '); // Replaces all other character before the '@' character with spaces
break;
}
if (y) // Stops for loop
{
break;
}
}
return x;
}
令我惊讶的是,我得到了
的相同结果"Gml.cm"
是否知道我的循环或开关语句有什么问题?我似乎找不到引起这个问题的问题。
您似乎只是想从电子邮件地址获得域。很容易:假设您的字符串中有@
,只需返回以下内容:
return x.substring(x.indexOf('@') + 1);
(感谢Grzegorzgórkiewicz在评论中指出了我的一对一错误)
,但是,上面代码中出现意外输出的原因是您误解了String.replace(char, char)
的作用:它替换了第一个参数的所有 All 将第二个参数替换为第二个参数。这也许令人困惑,因为也有replaceAll
方法。这样做相同,但使用正则表达式进行匹配和替换。
与代码类似的最佳方法是使用StringBuilder
:这使您可以在当前索引处突变单个字符:
StringBuilder s = new StringBuilder(x);
for (int a = 0; a < x.length(); a++) {
char c = s.charAt(a);
s.setCharAt(a, ' ');
if (c == '@') {
// Replace the spaces, etc, like above.
x = s.toString().replaceAll("\s+", "");
return x;
}
}
x = s.toString();
return x;
请注意,其中一种情况是default
的两个案例开关更容易以条件为条件:y
变量大概只是存在以帮助您打破循环;如果您不在switch
中,则可以直接使用break
(无论如何您都可以使用标记的休息时间或return
)。
x.replace(x.charAt(a), ' ')
取代了它发现的字符。就像它在您的循环中找到了A,然后我也从gmail
中替换了A。
在您的字符串DannyKrosis@Gmail.com
中,有一个,我在 @之前找到了它,因此x.replace(x.charAt(a), ' ')
从gmail
替换a
和i
。
replace
方法替换了与给定字符匹配的所有字符,而不是仅在给定索引中替换
如果要在 @之后获得值,则只需使用LookBehind Regex:
(?<=@).*
由于其他两个帖子已经通过您的代码解决了问题,并建议解决您的目标,我只想在答案中分享替代方案。
public static void main(String[] args) {
String x = "DannyKrosis@Gmail.com";
boolean y = false;
for (int a = 0; a < x.length(); a++) {
switch (x.charAt(a)) {
case '@':
x = replaceCharAt(x, a, ' ');
x = x.replaceAll("\s+", "");
y = true; // Stops for loop
break;
default:
x = replaceCharAt(x, a, ' ');
break;
}
if (y) {
break;
}
}
System.out.println(x); // prints "Gmail.com"
}
public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}