Java:获取字符串中匹配位置的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2615749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: method to get position of a match in a String?
提问by hhh
String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
采纳答案by polygenelubricants
The family of methods that does this are:
执行此操作的方法系列是:
Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].
返回此字符串中第一次(或最后一次)出现的指定子字符串的索引[从指定索引开始向前(或向后)搜索]。
String text = "0123hello9012hello8901hello7890";
String word = "hello";
System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"
// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
System.out.println(i);
} // prints "4", "13", "22"
// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
System.out.println(i);
} // prints "22", "13", "4"
回答by Anthony Pegram
Use string.indexOf to get the starting index.
使用 string.indexOf 获取起始索引。
回答by Michael Mrozek
回答by hhh
You can get all matches in a file simply by assigning inside while-loop, cool:
您可以通过在 while 循环中进行分配来获取文件中的所有匹配项,很酷:
$ javac MatchTest.java
$ java MatchTest
1
16
31
46
$ cat MatchTest.java
import java.util.*;
import java.io.*;
public class MatchTest {
public static void main(String[] args){
String match = "hello";
String text = "hello0123456789hello0123456789hello1234567890hello3423243423232";
int i =0;
while((i=(text.indexOf(match,i)+1))>0)
System.out.println(i);
}
}
回答by Khan
import java.util.StringTokenizer;
public class Occourence {
public static void main(String[] args) {
String key=null,str ="my name noorus my name noorus";
int i=0,tot=0;
StringTokenizer st=new StringTokenizer(str," ");
while(st.hasMoreTokens())
{
tot=tot+1;
key = st.nextToken();
while((i=(str.indexOf(key,i)+1))>0)
{
System.out.println("position of "+key+" "+"is "+(i-1));
}
}
System.out.println("total words present in string "+tot);
}
}
回答by Sayed
int match_position=text.indexOf(match);
回答by Suragch
Finding a single index
查找单个索引
As others have said, use text.indexOf(match)
to find a single match.
正如其他人所说,用于text.indexOf(match)
查找单个匹配项。
String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
Finding multiple indexes
查找多个索引
Because of @StephenC's commentabout code maintainability and my own difficulty in understanding @polygenelubricants' answer, I wanted to find another way to get all the indexes of a match in a text string. The following code (which is modified from this answer) does so:
由于@StephenC关于代码可维护性的评论以及我自己在理解@polygenelubricants 的回答方面的困难,我想找到另一种方法来获取文本字符串中匹配项的所有索引。下面的代码(从这个答案修改)这样做:
String text = "0123hello9012hello8901hello7890";
String match = "hello";
int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) { // indexOf returns -1 if no match found
System.out.println(index);
index = text.indexOf(match, index + matchLength);
}
回答by JPeraita
If you're going to scan for 'n' matches of the search string, I'd recommend using regular expressions. They have a steep learning curve, but they'll save you hours when it comes to complex searches.
如果您要扫描搜索字符串的“n”个匹配项,我建议您使用正则表达式。它们具有陡峭的学习曲线,但在复杂搜索方面可为您节省数小时。
回答by Nitika Goswami
I have some big code but working nicely....
我有一些大代码,但运行良好....
class strDemo
{
public static void main(String args[])
{
String s1=new String("The Ghost of The Arabean Sea");
String s2=new String ("The");
String s6=new String ("ehT");
StringBuffer s3;
StringBuffer s4=new StringBuffer(s1);
StringBuffer s5=new StringBuffer(s2);
char c1[]=new char[30];
char c2[]=new char[5];
char c3[]=new char[5];
s1.getChars(0,28,c1,0);
s2.getChars(0,3,c2,0);
s6.getChars(0,3,c3,0); s3=s4.reverse();
int pf=0,pl=0;
char c5[]=new char[30];
s3.getChars(0,28,c5,0);
for(int i=0;i<(s1.length()-s2.length());i++)
{
int j=0;
if(pf<=1)
{
while (c1[i+j]==c2[j] && j<=s2.length())
{
j++;
System.out.println(s2.length()+" "+j);
if(j>=s2.length())
{
System.out.println("first match of(The) :->"+i);
}
pf=pf+1;
}
}
}
for(int i=0;i<(s3.length()-s6.length()+1);i++)
{
int j=0;
if(pl<=1)
{
while (c5[i+j]==c3[j] && j<=s6.length())
{
j++;
System.out.println(s6.length()+" "+j);
if(j>=s6.length())
{
System.out.println((s3.length()-i-3));
pl=pl+1;
}
}
}
}
}
}
回答by shravan
//finding a particular word any where inthe string and printing its index and occurence
class IndOc
{
public static void main(String[] args)
{
String s="this is hyderabad city and this is";
System.out.println("the given string is ");
System.out.println("----------"+s);
char ch[]=s.toCharArray();
System.out.println(" ----word is found at ");
int j=0,noc=0;
for(int i=0;i<ch.length;i++)
{
j=i;
if(ch[i]=='i' && ch[j+1]=='s')
{
System.out.println(" index "+i);
noc++;
}
}
System.out.println("----- no of occurences are "+noc);
}
}