문자열에 단일 문자가 나타나는지 어떻게 확인할 수 있습니까?
Java에는 조건을 확인하는 방법이 있습니다.
"이 단일 문자가 문자열 x에 전혀 표시됩니까?"
루프 를 사용 하지 않고 ?
사용할 수 있습니다 string.indexOf('a')
.
(가) 경우
'a'
에 존재이고string
, 상기 인덱스 (> = 0)을 리턴한다. 그렇지 않으면 -1을 반환합니다. 따라서 음이 아닌 반환 값은을 의미합니다'a' is present in the string
.
String.contains()
문자열에 지정된 문자 값 시퀀스가 포함되어 있는지 확인합니다.String.indexOf()
지정된 문자 또는 하위 문자열이 처음 나타나는 문자열 내에서 색인을 반환합니다 (이 방법에는 4 가지 변형이 있음)
원래 포스터가 정확히 무엇을 요구하는지 잘 모르겠습니다. indexOf (...)와 contains (...) 둘 다 내부적으로 루프를 사용하기 때문에 아마도 루프없이 이것이 가능한지 여부를 찾고 있습니까? 나는 두 가지 방법을 생각할 수있다. 물론 하나는 재발이다.
public boolean containsChar(String s, char search) {
if (s.length() == 0)
return false;
else
return s.charAt(0) == search || containsChar(s.substring(1), search);
}
다른 하나는 훨씬 덜 우아하지만 완벽합니다 ... :
/**
* Works for strings of up to 5 characters
*/
public boolean containsChar(String s, char search) {
if (s.length() > 5) throw IllegalArgumentException();
try {
if (s.charAt(0) == search) return true;
if (s.charAt(1) == search) return true;
if (s.charAt(2) == search) return true;
if (s.charAt(3) == search) return true;
if (s.charAt(4) == search) return true;
} catch (IndexOutOfBoundsException e) {
// this should never happen...
return false;
}
return false;
}
물론 더 길고 긴 문자열을 지원해야하므로 줄 수가 늘어납니다. 그러나 루프 / 재귀는 전혀 없습니다. length ()가 루프를 사용하는 것이 걱정된다면 길이 검사를 제거 할 수도 있습니다.
String temp = "abcdefghi";
if(temp.indexOf("b")!=-1)
{
System.out.println("there is 'b' in temp string");
}
else
{
System.out.println("there is no 'b' in temp string");
}
문자열에없는 것이 있는지 확인하려면 최소한 문자열의 각 문자를 확인해야합니다. 따라서 루프를 명시 적으로 사용하지 않더라도 동일한 효율성을 갖습니다. 즉, str.contains ( ""+ char)를 사용해 볼 수 있습니다.
동일한 문자열을 자주 확인해야하는 경우 사전에 문자 발생을 계산할 수 있습니다. 이것은 긴 배열에 포함 된 비트 배열을 사용하는 구현입니다.
public class FastCharacterInStringChecker implements Serializable {
private static final long serialVersionUID = 1L;
private final long[] l = new long[1024]; // 65536 / 64 = 1024
public FastCharacterInStringChecker(final String string) {
for (final char c: string.toCharArray()) {
final int index = c >> 6;
final int value = c - (index << 6);
l[index] |= 1L << value;
}
}
public boolean contains(final char c) {
final int index = c >> 6; // c / 64
final int value = c - (index << 6); // c - (index * 64)
return (l[index] & (1L << value)) != 0;
}}
String
클래스 에서 2 개의 메소드를 사용할 수 있습니다 .
String.contains()
문자열에 지정된 문자 값 시퀀스가 포함되어 있는지 확인합니다.String.indexOf()
지정된 문자 또는 하위 문자열이 처음 나타나는 문자열 내에서 색인을 반환하거나 문자를 찾을 수없는 경우 -1을 반환합니다 (이 방법에는 4 가지 변형이 있음)
방법 1 :
String myString = "foobar";
if (myString.contains("x") {
// Do something.
}
방법 2 :
String myString = "foobar";
if (myString.indexOf("x") >= 0 {
// Do something.
}
링크 : Zach Scrivena
예, 문자열 클래스에서 indexOf () 메소드를 사용하십시오. 이 방법에 대한 API 설명서를 참조하십시오
package com;
public class _index {
public static void main(String[] args) {
String s1="be proud to be an indian";
char ch=s1.charAt(s1.indexOf('e'));
int count = 0;
for(int i=0;i<s1.length();i++) {
if(s1.charAt(i)=='e'){
System.out.println("number of E:=="+ch);
count++;
}
}
System.out.println("Total count of E:=="+count);
}
}
String s="praveen";
boolean p=s.contains("s");
if(p)
System.out.println("string contains the char 's'");
else
System.out.println("string does not contains the char 's'");
산출
string does not contains the char 's'
static String removeOccurences(String a, String b)
{
StringBuilder s2 = new StringBuilder(a);
for(int i=0;i<b.length();i++){
char ch = b.charAt(i);
System.out.println(ch+" first index"+a.indexOf(ch));
int lastind = a.lastIndexOf(ch);
for(int k=new String(s2).indexOf(ch);k > 0;k=new String(s2).indexOf(ch)){
if(s2.charAt(k) == ch){
s2.deleteCharAt(k);
System.out.println("val of s2 : "+s2.toString());
}
}
}
System.out.println(s1.toString());
return (s1.toString());
}
you can use this code. It will check the char is present or not. If it is present then the return value is >= 0 otherwise it's -1. Here I am printing alphabets that is not present in the input.
import java.util.Scanner;
public class Test {
public static void letters()
{
System.out.println("Enter input char");
Scanner sc = new Scanner(System.in);
String input = sc.next();
System.out.println("Output : ");
for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
if(input.toUpperCase().indexOf(alphabet) < 0)
System.out.print(alphabet + " ");
}
}
public static void main(String[] args) {
letters();
}
}
//Ouput Example
Enter input char
nandu
Output :
B C E F G H I J K L M O P Q R S T V W X Y Z
아래는 당신이 찾고 있던 것입니까?
int index = string.indexOf(character);
return index != -1 && string.lastIndexOf(character) != index;
You won't be able to check if char appears at all in some string without atleast going over the string once using loop / recursion ( the built-in methods like indexOf also use a loop )
If the no. of times you look up if a char is in string x is more way more than the length of the string than I would recommend using a Set data structure as that would be more efficient than simply using indexOf
String s = "abc";
// Build a set so we can check if character exists in constant time O(1)
Set<Character> set = new HashSet<>();
int len = s.length();
for(int i = 0; i < len; i++) set.add(s.charAt(i));
// Now we can check without the need of a loop
// contains method of set doesn't use a loop unlike string's contains method
set.contains('a') // true
set.contains('z') // false
Using set you will be able to check if character exists in a string in constant time O(1) but you will also use additional memory ( Space complexity will be O(n) ).
I used the string.includes() method for this which returns true or false if the string or character is found. See the below documentation.
https://www.w3schools.com/jsref/jsref_includes.asp
//this is only the main... you can use wither buffered reader or scanner
string s;
int l=s.length();
int f=0;
for(int i=0;i<l;i++)
{
char ch1=s.charAt(i);
for(int j=0;j<l;j++)
{
char ch2=charAt(j);
if(ch1==ch2)
{
f=f+1;
s.replace(ch2,'');
}
f=0;
}
}
//if replacing with null does not work then make it space by using ' ' and add a if condition on top.. checking if its space if not then only perform the inner loop...
참고URL : https://stackoverflow.com/questions/506105/how-can-i-check-if-a-single-character-appears-in-a-string
'Programing' 카테고리의 다른 글
jq를 사용하여 객체의 변수 값을 기준으로 객체를 선택하십시오. (0) | 2020.05.16 |
---|---|
N "고유 한"색상을 자동으로 생성하는 방법은 무엇입니까? (0) | 2020.05.16 |
힘내 비난 : 통계 (0) | 2020.05.15 |
Git 브랜칭 : 마스터 vs. 오리진 / 마스터 vs. 리모트 / 오리진 / 마스터 (0) | 2020.05.15 |
SQL : WHERE 절 내의 IF 절 (0) | 2020.05.15 |