gpt4 book ai didi

java - 如何从字符串数组中的字符串中查找重复的字符值

转载 作者:行者123 更新时间:2023-12-02 11:39:36 30 4
gpt4 key购买 nike

我试图显示数组中的重复字符串,但代码不起作用。例如:在单词“arrow”r 中出现两次 shoq,代码应该显示输出“r”。但它没有显示任何东西

public class duplicatearray {
public static void main(String[] args)
{
String[] s={"arrow"};
for(int i=0;i<s.length;i++)
{
for(int j=i+1;j<s.length;j++)
{
if(s[i].equals(s[j]))
{
System.out.println("Duplicate value"+s[i]);
}
}
}

}
}

最佳答案

For example:In the word "arrow" r is coming two times shoq the code should display the output 'r'.

您正在检查两个字符串。您想在哪里检查重复字符

if(s[i].equals(s[j]))

应该是

if(s[i].charAt(j) == s[i].charAt(j+1))

然后它检查相同字符串中的字符。并且也在打印语句中

System.out.println("Duplicate value"+s[i].charAt(j));

你的循环也错了,你应该从第 0 个字符开始

for(int j= 0 ;j<s[i].length() -1 ;j++)

所以总体来说应该是

String[] s = { "arrow" };
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length() - 1; j++) {
if (s[i].charAt(j) == s[i].charAt(j + 1)) {
System.out.println("Duplicate value : " + s[i].charAt(j));
}
}
}

关于java - 如何从字符串数组中的字符串中查找重复的字符值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48678824/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com