programing

문자열에서 단일 문자를 인덱스별로 제거하는 방법

cafebook 2023. 9. 10. 12:38
반응형

문자열에서 단일 문자를 인덱스별로 제거하는 방법

자바에서 문자열의 개별 문자에 액세스하기 위해 다음과 같은 작업을 수행합니다.String.charAt(2)의 개별 를 제거할 수 있는 이 있습니까? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

이와 같은 것:

if(String.charAt(1) == String.charAt(2){
   //I want to remove the individual character at index 2. 
}

사용할 수도 있습니다.StringBuilder가변적인 클래스

StringBuilder sb = new StringBuilder(inputString);

이것은 다른 많은 돌연변이 방법들과 함께 방법을 가지고 있습니다.

삭제해야 할 문자만 삭제하면 다음과 같은 결과가 나옵니다.

String resultString = sb.toString();

이렇게 하면 불필요한 문자열 개체가 생성되지 않습니다.

replace라고 하는 Java String 메서드를 사용할 수 있습니다. 이 메서드는 첫 번째 매개 변수와 일치하는 모든 문자를 두 번째 매개 변수로 바꿉니다.

String a = "Cool";
a = a.replace("o","");

한 가지 가능성:

String result = str.substring(0, index) + str.substring(index+1);

Java의 문자열은 불변이므로 결과는 새 문자열(2개의 중간 문자열 개체와 마찬가지로)입니다.

아닙니다. 자바의 문자열은 불변하기 때문입니다.원하지 않는 문자를 제거하는 새 문자열을 만들어야 합니다.

의 문자를 의 하는 를 하는 cidxstr하고 새 과 을 하고 이 하십시오 을 된다는 하십시오 을 된다는 이 과

String newstr = str.substring(0, idx) + str.substring(idx + 1);
String str = "M1y java8 Progr5am";

CharAt() 삭제

StringBuilder build = new StringBuilder(str);
System.out.println("Pre Builder : " + build);
    build.deleteCharAt(1);  // Shift the positions front.
    build.deleteCharAt(8-1);
    build.deleteCharAt(15-2);
System.out.println("Post Builder : " + build);

교체하다 ()

StringBuffer buffer = new StringBuffer(str);
    buffer.replace(1, 2, ""); // Shift the positions front.
    buffer.replace(7, 8, "");
    buffer.replace(13, 14, "");
System.out.println("Buffer : "+buffer);

차[차]

char[] c = str.toCharArray();
String new_Str = "";
    for (int i = 0; i < c.length; i++) {
        if (!(i == 1 || i == 8 || i == 15)) 
            new_Str += c[i];
    }
System.out.println("Char Array : "+new_Str);

Strings를 수정하려면 StringBuilder에 대해 읽어보십시오. StringBuilder는 불변 String을 제외하고는 변경할 수 없기 때문입니다.다른 작업은 https://docs.oracle.com/javase/tutorial/java/data/buffers.html 에서 확인할 수 있습니다.아래 코드 조각은 StringBuilder를 만든 다음 주어진 String을 추가한 다음 String에서 첫 번째 문자를 삭제한 다음 StringBuilder에서 String으로 다시 변환합니다.

StringBuilder sb = new StringBuilder();

sb.append(str);
sb.deleteCharAt(0);
str = sb.toString();

다음 코드를 생각해 보십시오.

public String removeChar(String str, Integer n) {
    String front = str.substring(0, n);
    String back = str.substring(n+1, str.length());
    return front + back;
}

(거대한) regexp 기계를 사용할 수도 있습니다.

inputString = inputString.replaceFirst("(?s)(.{2}).(.*)", "$1$2");
  • "(?s)" -regexp에서 일반 문자와 같은 새 줄을 처리합니다(경우에 따라).
  • "(.{2})" - 2개의 를 수집합니다. $1히 2는것의룹것는를p히2$1 .
  • "." -인덱스 2에 있는 임의의 문자(짜낼 것).
  • "(.*)" -나머지 입력 문자열을 수집하는 $2 그룹.
  • "$1$2" -그룹 $1과 그룹 $2를 합치는 것입니다.

문자열 문자열에서 특정 int 인덱스의 char를 제거하려면 다음을 수행합니다.

    public static String removeCharAt(String str, int index) {

        // The part of the String before the index:
        String str1 = str.substring(0,index);

        // The part of the String after the index:            
        String str2 = str.substring(index+1,str.length());

        // These two parts together gives the String without the specified index
        return str1+str2;

    }

교체 방법을 사용하면 문자열의 단일 문자를 변경할 수 있습니다.

string= string.replace("*", "");

string class의 replaceFirst 함수를 사용합니다.당신이 사용할 수 있는 교체 기능은 매우 다양합니다.

문자 제거에 대한 논리적 제어가 필요한 경우 이를 사용합니다.

String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);

그런 통제가 필요하지 않다면 오스카나 베쉬가 언급한 것을 사용하면 됩니다.그들은 딱 맞습니다.

문자열에서 문자를 제거하는 가장 쉬운 방법

String str="welcome";
str=str.replaceFirst(String.valueOf(str.charAt(2)),"");//'l' will replace with "" 
System.out.println(str);//output: wecome
public class RemoveCharFromString {
    public static void main(String[] args) {
        String output = remove("Hello", 'l');
        System.out.println(output);
    }

    private static String remove(String input, char c) {

        if (input == null || input.length() <= 1)
            return input;
        char[] inputArray = input.toCharArray();
        char[] outputArray = new char[inputArray.length];
        int outputArrayIndex = 0;
        for (int i = 0; i < inputArray.length; i++) {
            char p = inputArray[i];
            if (p != c) {
                outputArray[outputArrayIndex] = p;
                outputArrayIndex++;
            }

        }
        return new String(outputArray, 0, outputArrayIndex);

    }
}

대부분의 사용 사례에서 다음을 사용합니다.StringBuilder아니면substring(이미 답변한 바와 같이) 좋은 접근 방식입니다.그러나 성능에 중요한 코드의 경우 이 방법이 좋은 대안이 될 수 있습니다.

/**
 * Delete a single character from index position 'start' from the 'target' String.
 * 
 * ````
 * deleteAt("ABC", 0) -> "BC"
 * deleteAt("ABC", 1) -> "B"
 * deleteAt("ABC", 2) -> "C"
 * ````
 */
public static String deleteAt(final String target, final int start) {
    return deleteAt(target, start, start + 1);
} 


/**
 * Delete the characters from index position 'start' to 'end' from the 'target' String.
 * 
 * ````
 * deleteAt("ABC", 0, 1) -> "BC"
 * deleteAt("ABC", 0, 2) -> "C"
 * deleteAt("ABC", 1, 3) -> "A"
 * ````
 */
public static String deleteAt(final String target, final int start, int end) {
    final int targetLen = target.length();
    if (start < 0) {
        throw new IllegalArgumentException("start=" + start);
    }
    if (end > targetLen || end < start) {
        throw new IllegalArgumentException("end=" + end);
    }
    if (start == 0) {
        return end == targetLen ? "" : target.substring(end);
    } else if (end == targetLen) {
        return target.substring(0, start);
    }
    final char[] buffer = new char[targetLen - end + start];
    target.getChars(0, start, buffer, 0);
    target.getChars(end, targetLen, buffer, start);
    return new String(buffer);
}

*StringBuilder를 사용하여 문자열 값을 삭제하고 charAt를 삭제할 수 있습니다.

String s1 = "aabc";
StringBuilder sb = new StringBuilder(s1);
for(int i=0;i<sb.length();i++)
{
  char temp = sb.charAt(0);
  if(sb.indexOf(temp+"")!=1)
  {                             
    sb.deleteCharAt(sb.indexOf(temp+""));   
  }
}

주어진 문자열에서 단일 문자를 제거하려면 유용하기를 바라며 내 방법을 찾아주세요. str.replace모두를 사용하여 문자열을 제거했지만 주어진 문자열에서 문자를 제거하는 많은 방법이 있지만 모든 방법을 바꾸는 것을 선호합니다.

문자 제거 코드:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;


public class Removecharacter 
{

    public static void main(String[] args) 
    {
        String result = removeChar("Java", 'a');
        String result1 = removeChar("Edition", 'i');

         System.out.println(result + " " + result1);

    }


    public static String removeChar(String str, char c) {
        if (str == null)
        {
            return null;
        }
        else
        {   
        return str.replaceAll(Character.toString(c), "");
        }
    }


}

콘솔 이미지:

콘솔의 첨부된 이미지를 찾아주시기 바랍니다.

enter image description here

물어봐 줘서 고마워요.:)

public static String removechar(String fromString, Character character) {
    int indexOf = fromString.indexOf(character);
    if(indexOf==-1) 
        return fromString;
    String front = fromString.substring(0, indexOf);
    String back = fromString.substring(indexOf+1, fromString.length());
    return front+back;
}
           BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
   String line1=input.readLine();
   String line2=input.readLine();
         char[]  a=line2.toCharArray();
          char[] b=line1.toCharArray();
           loop: for(int t=0;t<a.length;t++) {

            char a1=a[t];
           for(int t1=0;t1<b.length;t1++) {
               char b1=b[t1];  
               if(a1==b1) {
                   StringBuilder sb = new StringBuilder(line1);
                   sb.deleteCharAt(t1);
                   line1=sb.toString();
                   b=line1.toCharArray();
                   list.add(a1);
                   continue  loop;   
               }


            }

저는 이런 질문이 있을 때 항상 "Java Gurus는 무엇을 할까요?"라고 물어봅니다. :)

그리고 저는 이 경우에, 저는 그것에 대해 대답할 것입니다.String.trim().

여기에 더 많은 다듬어진 문자를 사용할 수 있도록 하는 구현에 대한 추론이 있습니다.

하지만 원래 트림을 사용하면 모든 차를 제거할 수 있습니다.<= ' ', 따라서 원하는 결과를 얻기 위해서는 원본과 이것을 결합해야 할 수도 있습니다.

String trim(String string, String toTrim) {
    // input checks removed
    if (toTrim.length() == 0)
        return string;

    final char[] trimChars = toTrim.toCharArray();
    Arrays.sort(trimChars);

    int start = 0;
    int end = string.length();

    while (start < end && 
        Arrays.binarySearch(trimChars, string.charAt(start)) >= 0)
        start++;

    while (start < end && 
        Arrays.binarySearch(trimChars, string.charAt(end - 1)) >= 0)
        end--;

    return string.substring(start, end);
}
public String missingChar(String str, int n) {
  String front = str.substring(0, n);

// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.

String back = str.substring(n+1, str.length());
  return front + back;
}

문자열에서 문자 또는 문자 그룹을 제거하는 유틸리티 클래스를 구현했습니다.Regexp를 사용하지 않아서 빠른 것 같습니다.누군가에게 도움이 되었으면 좋겠군요!

package your.package.name;

/**
 * Utility class that removes chars from a String.
 * 
 */
public class RemoveChars {

    public static String remove(String string, String remove) {
        return new String(remove(string.toCharArray(), remove.toCharArray()));
    }

    public static char[] remove(final char[] chars, char[] remove) {

        int count = 0;
        char[] buffer = new char[chars.length];

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

            boolean include = true;
            for (int j = 0; j < remove.length; j++) {
                if ((chars[i] == remove[j])) {
                    include = false;
                    break;
                }
            }

            if (include) {
                buffer[count++] = chars[i];
            }
        }

        char[] output = new char[count];
        System.arraycopy(buffer, 0, output, 0, count);

        return output;
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
        String remove = "AEIOU";

        System.out.println();
        System.out.println("Remove AEIOU: " + string);
        System.out.println("Result:       " + RemoveChars.remove(string, remove));
    }
}

출력은 다음과 같습니다.

Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result:       TH QCK BRWN FX JMPS VR TH LZY DG

예를 들어 문자열에 있는 a의 개수를 계산하려면 다음과 같이 수행할 수 있습니다.

if (string.contains("a"))
{
    numberOf_a++;
    string = string.replaceFirst("a", "");
}

언급URL : https://stackoverflow.com/questions/13386107/how-to-remove-single-character-from-a-string-by-index

반응형