gpt4 book ai didi

java - [Java]在没有 hashmap 的字符串中查找重复字符并设置

转载 作者:行者123 更新时间:2023-12-01 21:13:08 25 4
gpt4 key购买 nike

我编写了一个 Java 程序来查找字符串中的重复字符,无需使用 Hashmap 和 set。

下面是程序,

package practice;

public class Duplicate {

public static void main(String[] args) {

String src= "abcad";

char[] srcChar= src.toLowerCase().toCharArray();

int len=srcChar.length;
int j=0;
boolean flag=false;
char ch;

// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);


int k=0;

for(int i=0;i<len;i++)
{
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for(j=0;j<len;j++)
{
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if(srcChar[i]==srcChar[j])
{
k++;
}
}
if(k>1)
{
if(srcChar[i]>1)
{
System.out.println("This character "+srcChar[i]+" has repeated "+k+ " time");
}
else
{
System.out.println("There are no characters repeated in the given string");
}
}
k=0;
}
}
}

这里的输出是:

这个字符a已经重复了2次
该字符 a 已重复 2 次

在这里,我想要的输出如下这个字符a重复了2次

即不重复输出两次。由于字符“a”重复两次,因此输出也重复两次。

请帮助我获得一次输出而不是两次。

谢谢,

最佳答案

class PrintDuplicateCharacter 
{
public static void main(String[] args)
{

String str = "HelloJava";
char[] ch = str.toCharArray();
int i=0,j=0;
for(i=0;i<ch.length;i++)
{
int count = 0 ;
for( j = i+1;j<ch.length;j++)
{// 4 6 , 8 , 10
if(ch[i] == ch[j] )
{
count++;
}
}
if(count != 0)
{
System.out.print(str.charAt(i) + " Occured " + count + " time");
}


}



}
}

关于java - [Java]在没有 hashmap 的字符串中查找重复字符并设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40790268/

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