gpt4 book ai didi

java - 在Java中查找具有连续字符的字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:52:03 25 4
gpt4 key购买 nike

用 Java 编写一个函数,它接受一个字符串数组,并从字符串数组中仅返回那些连续重复特定字母的字符串,例如:如果 I/P 是

{"Dauresselam", "slab", "fuss", "boolean", "clap"}

那么O/P应该是

{"Dauresselam", "fuss", "boolean"}

我可以用

解决它
import java.util.Scanner;
public class doubleChars {
public static String[] getDoubles(String[]In)
{

int inLen=In.length;
String zoom[]=new String[inLen];
int count=0;
if(inLen==0)
{
return zoom;
}
for(int i=0;i<=inLen-1;i++)
{
String A=In[i];
//System.out.println(A);
int striLen=A.length();
for(int j=0;j<striLen-1;j++)
{

if(A.substring(j, j+1).equals(A.substring(j+1, j+2)))
{
zoom[count]=A;
count++;
break;
}
}

}
return zoom;
}
public static void main(String[] args)
{
char more='y';
int ab=0;
String[] res={};
String[] fillMe={"durres", "murres", "", "abcdeee", "boolean", "nger", "lagger"};
Scanner strobe=new Scanner(System.in);
System.out.println("Please enter the arraye of the string");
/*while(strobe.hasNext())
{
fillMe[ab]=strobe.next();

ab++;
}
*/
res=doubleChars.getDoubles(fillMe);
for(int k=0;k<res.length;k++)
{
if(res[k]==null)
{
break;
}
System.out.println(res[k]);
}
}
}

是否有办法使用正则表达式使其更短?

最佳答案

你可以使用 backreference :

([a-z])\1

Regular expression visualization

可视化 Debuggex


Java 示例:

String[] strings = { "Dauresselam", "slab", "fuss", "boolean", "clap" };

String regex = "([a-z])\\1";
Pattern pattern = Pattern.compile(regex);

for (String string : strings) {
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println(string);
}
}

打印:

Dauresselam
fuss
boolean

关于java - 在Java中查找具有连续字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20043633/

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