Java子字符是什么,什么是Java中最快的子字符串搜索方法

I need to implement a way to search substring (needles) in a list of string (haystack) using Java.

More specifically, my app has a list of user profiles. If I type some letters, for example, "Ja", and then search, then all the users whose name contains "ja" should show up. For instance, the result could be "Jack", "Jackson", "Jason", "Dijafu".

In Java, as I know, there are 3 build-in method to see search substring in a string.

string.contains()

string.indexOf()

regular expression. it is something like string.matches("ja"))

My question is: What are the runtimes of each method above? which one is the fastest or most efficient or most popular way to check if the list of string contains a given substring.

I know there exists some algorithms that do the same thing, such as Boyer–Moore string search algorithm, Knuth–Morris–Pratt algorithm and so on. I do not want to use them because I just have a small list of strings, and I think using them is kind of overkill for me right now. Also I have to type a lot of extra coding for such a non-build-in algorithm.

If you think my thoughts is not correct, please feel free to correct me.

解决方案String[] names = new String[]{"jack", "jackson", "jason", "dijafu"};

long start = 0;

long stop = 0;

//Contains

start = System.nanoTime();

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

names[i].contains("ja");

}

stop = System.nanoTime();

System.out.println("Contains: " + (stop-start));

//IndexOf

start = System.nanoTime();

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

names[i].indexOf("ja");

}

stop = System.nanoTime();

System.out.println("IndexOf: " + (stop-start));

//Matches

start = System.nanoTime();

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

names[i].matches("ja");

}

stop = System.nanoTime();

System.out.println("Matches: " + (stop-start));

Output:

Contains: 16677

IndexOf: 4491

Matches: 864018

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值