in the java search_Java - search a string in string array

In java do we have any method to find that a particular string is part of string array.

I can do in a loop which I would like to avoid.

e.g.

String [] array = {"AA","BB","CC" };

string x = "BB"

I would like a

if (some condition to tell whether x is part of array) {

do something

} else {

do something else

}

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

Do something like:

Arrays.asList(array).contains(x);

since that return true if the String x is present in the array (now converted into a list...)

Example:

if(Arrays.asList(array).contains(x)){

// is present ... :)

}

# Answer 2

You could also use the commons-lang library from Apache which provides the much appreciated method contains.

import org.apache.commons.lang.ArrayUtils;

public class CommonsLangContainsDemo {

public static void execute(String[] strings, String searchString) {

if (ArrayUtils.contains(strings, searchString)) {

System.out.println("contains.");

} else {

System.out.println("does not contain.");

}

}

public static void main(String[] args) {

execute(new String[] { "AA","BB","CC" }, "BB");

}

}

# Answer 3

This code will work for you:

bool count = false;

for(int i = 0; i < array.length; i++)

{

if(array[i].equals(x))

{

count = true;

break;

}

}

if(count)

{

//do some other thing

}

else

{

//do some other thing

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值