반응형
Java: 문자열에서 일치 위치를 가져오는 방법?
String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
이를 수행하는 방법 패밀리는 다음과 같습니다.
지정된 하위 문자열(지정된 인덱스에서 시작하는 앞으로(또는 뒤로) 검색) 처음 또는 마지막으로 발생한 문자열 내의 인덱스를 반환합니다.
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"
이것은 regex를 사용하여 동작합니다.
String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}
출력:
색인 2 - 5에서 '사랑'을 찾았습니다.
일반 규칙:
- 왼쪽에서 오른쪽으로 정규식을 검색하여 일치 문자를 사용한 후에는 재사용할 수 없습니다.
text.indexOf(match);
단일 인덱스 찾기
다른 사람들이 말한 것처럼text.indexOf(match)
일치하는 것을 찾을 수 있습니다.
String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
여러 인덱스 찾기
코드 유지보수에 대한 @StephenC의 코멘트와 @polygenerelubicants의 답변을 이해하기 어려웠기 때문에 텍스트 문자열에 일치하는 인덱스를 모두 가져올 수 있는 다른 방법을 찾고 싶었습니다.(이 답변에서 변경된) 다음 코드가 이를 수행합니다.
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);
}
내부에서 while-loop, cool을 할당하는 것만으로 파일 내의 모든 일치를 얻을 수 있습니다.
$ 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);
}
}
int match_position=text.indexOf(match);
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);
}
}
큰 코드를 가지고 있지만, 잘 동작하고 있습니다.
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;
}
}
}
}
}
}
//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);
}
}
String match = "hello";
String text = "0123456789hello0123456789hello";
int j = 0;
String indxOfmatch = "";
for (int i = -1; i < text.length()+1; i++) {
j = text.indexOf("hello", i);
if (i>=j && j > -1) {
indxOfmatch += text.indexOf("hello", i)+" ";
}
}
System.out.println(indxOfmatch);
검색 문자열의 일치하는 'n'개를 검색하려면 정규 표현을 사용하는 것이 좋습니다.학습 곡선이 빠르지만 복잡한 검색에 필요한 시간을 절약할 수 있습니다.
문자열에서 찾을 수 있는 문자는 무엇입니까?예스 또는 노
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SubStringtest {
public static void main(String[] args)throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the string");
String str=br.readLine();
System.out.println("enter the character which you want");
CharSequence ch=br.readLine();
boolean bool=str.contains(ch);
System.out.println("the character found is " +bool);
int position=str.indexOf(ch.toString());
while(position>=0){
System.out.println("the index no of character is " +position);
position=str.indexOf(ch.toString(),position+1);
}
}
}
public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
{
int iii1=0;
int iii2=0;
int iii3=0;
while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
// iii2 is the number of the occurences
if(iii2>0) {
positions_ = new int[iii2];
while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
positions_[iii3] = iii1-1;
iii3 = iii3 + 1;
System.out.println("position=" + positions_[iii3 - 1]);
}
}
return iii2;
}
언급URL : https://stackoverflow.com/questions/2615749/java-method-to-get-position-of-a-match-in-a-string
반응형
'programing' 카테고리의 다른 글
Axios 호출에서 Vuejs img 요소로 이미지를 표시하려면 어떻게 해야 합니까?효과가 있는 것을 본 적이 없다 (0) | 2022.09.03 |
---|---|
IntelliJ에서 이 기호는 무엇을 의미합니까? ('J'가 들어간 파일 이름의 왼쪽 아래 모서리에 있는 빨간색 원) (0) | 2022.09.03 |
Java 메모리 누전 검출 방법 (0) | 2022.09.03 |
Vue js에서 여러 페이지(컴포넌트)를 동적으로 사용 (0) | 2022.09.03 |
Vue 컴포넌트 - 렌더링 위치가 잘못됨 (0) | 2022.09.03 |