한 문자열에 동일한 유형의 문자가 몇 개인 지 알아야합니다.한 문자열에 같은 문자가 있습니다.
나는 시도이
String x ="(3+3)*(4-2)";
int a = x.indexOf("(");
하지만 나에게 첫 번째 인덱스
한 문자열에 동일한 유형의 문자가 몇 개인 지 알아야합니다.한 문자열에 같은 문자가 있습니다.
나는 시도이
String x ="(3+3)*(4-2)";
int a = x.indexOf("(");
하지만 나에게 첫 번째 인덱스
별도의 함수에 넣어 더 좋을 것 같아를 이 :
System.out.println(get_count("(3+3)*(4-2)", '('));
// Output: 2
사용을 줄 것으로 StringUtils.countMatches
StringUtils.countMatches(value,"(");
또는 내가 COU 몇 가지 방법이있다
public static int countMatches(String value, String valueToCount) {
if (value.isEmpty() || valueToCount.isEmpty()) {
return 0;
}
int count = 0;
int index = 0;
while ((index = value.indexOf(valueToCount, index)) != -1) {
count++;
index += valueToCount.length();
}
return count;
}
LD의이 일을 생각하지만, 간단한 중 하나는 .... String
문자를 통해 간단하게 루프에
String x ="(3+3)*(4-2)";
int count = 0;
for (char c : x.toCharArray()) {
if (c == '(') {
count++;
}
}
System.out.println(count);
이 될 것입니다 그리고 그것을 할 수있다해서 ... 당신은 조금 정규 표현식을 사용할 수 있습니다. ... (나는, 과잉 알고)이 같은
Pattern p = Pattern.compile("\\(");
Matcher matcher = p.matcher(x);
while (matcher.find()) {
count++;
}
System.out.println(count);
뭔가가 당신을 위해 일해야합니다
int getCountOfSubstring(String haystack, String needle) {
int count = 0;
while(haystack.indexOf(needle) != -1) {
count++;
haystack = haystack.substring(tmp.indexOf(needle);
}
return count;
}
그 위입니다 당신이 먼저 charArray에 건초 더미를 줄이는 방법, 및 루프를 바람직 할 수있다 나는 당신은 오직 한 명의 성격만을 찾고 있습니다.
당신은 루프를 사용하고 다른 방법 indexOf(int, int)
사용할 수 있습니다
// accepts a string and a char to find the number of occurrences of
public static int get_count(String s, char c) {
int count = 0; // count initially 0
for (int i = 0; i < s.length(); i++) // loop through the whole string
if (s.charAt(i) == c)
count ++; // increment every time an occurrence happens
return count; // return the count in the end
}
당신은 다음과 같이 호출 할 수 있습니다
String x ="(3+3)*(4-2)";
int a = x.indexOf("(");
while (a >= 0) {
System.out.println("Char '(' found at: "+a);
a = x.indexOf('(', a+1);
}
오, 나는 다른 모든 사람들 사이의 그 대답을 간과했다. 그 방법이 있다는 것을 알고 있고 오버 헤드없이 답을 제공하는 사람들이 있다는 것을 보는 것이 좋습니다. – Holger
아래 코드는 원하는 작업을 수행합니다. 성능이 중요한 경우이를 사용하여 최적화를 수행 할 수 있습니다. 보다 우아한 솔루션을 원한다면 자바의 regex 라이브러리를 살펴보십시오.
int occurences = 0;
String x ="(3+3)*(4-2)";
char tolookfor = '(';
for(int i = 0; i < x.length() ; i++)
{
if(x.charAt(i) == tolookfor)
occurences++;
}
이
String x ="(3+3)*(4-2)";
char[] arr=x.toCharArray();
Map<String,Integer> map=new HashMap<>();
for(int i=0;i<arr.length;i++){
Integer upTo=map.get(String.valueOf(arr[i]));
if (upTo==null) {
upTo=0;
}
map.put(String.valueOf(arr[i]),upTo+1) ;
}
for (Map.Entry<String,Integer> entry:map.entrySet()){
System.out.println("Number of "+entry.getKey()+" in this string is: "+entry.getValue());
}
밖으로
Number of 3 in this string is: 2
Number of 2 in this string is: 1
Number of 4 in this string is: 1
Number of * in this string is: 1
Number of + in this string is: 1
Number of (in this string is: 2
Number of) in this string is: 2
Number of - in this string is: 1
그것은 같은 간단한 질문에 대한 답변이 얼마나 복잡한 믿을를 넣어 시도 할 수 있습니다.
x.indexOf("(");
하지만 나에게 더 발생을 찾을 수있는 첫 번째 인덱스
사용 x.indexOf("(", fromIndex);
을주고있다. 포인트.
그런데 하나의 문자를 찾으려면 x.indexOf('(');
과 x.indexOf('(', fromIndex);
을 사용하면 더 효율적입니다.
int count=0;
for(int pos=s.indexOf('('); pos!=-1; pos=s.indexOf('(', pos+1)) count++;
. 그러나 메소드의 코드를 복사 할 때 두 번째 매개 변수의 이름을 정규 표현식처럼 취급하지 않으므로 "regex"로 바꾸면 안됩니다. 정확한 매칭 만 수행하는'String.indexOf'를 호출하고 있습니다. – Holger