programing

문자열에서 단일 문자를 제거하는 방법

itsource 2022. 8. 14. 10:40
반응형

문자열에서 단일 문자를 제거하는 방법

의 개개의 String이 있습니다.String.charAt(2)Java String은 Java String String String String String은 Java String String String String String String String String String String String String String Str

다음과 같은 경우:

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의 문자열은 불변하기 때문에 결과는 새로운 String(및2개의 중간 String 오브젝트)입니다.

String str = "M1y java8 Progr5am";

deleteCharAt()

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);

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

의 문자를 c 포지션으로idxstr다음과 같은 작업을 수행하고 새 문자열이 작성된다는 점에 유의하십시오.

String newstr = str.substring(0, idx) + str.substring(idx + 1);

다음 코드를 고려합니다.

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

String을 수정하려면 String Builder에 대해 읽어보십시오.String Builder는 불변의 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();

(대규모) regexp 머신을 사용할 수도 있습니다.

inputString = inputString.replaceFirst("(?s)(.{2}).(.*)", "$1$2");
  • "(?s)" -는 regexp에 통상의 문자와 같이 새로운 행을 처리하도록 지시합니다(만일의 경우).
  • "(.{2})" -를 수집합니다. $1은 $1입니다.
  • "." -의 2 、 압 2 、 ) )
  • "(.*)" -2 2달러 、 string inputString 、 stringstring22222222 。
  • "$1$2" -과1달러 를2달러 22달러 22달러 。

치환 방식을 사용하면 문자열의 단일 문자를 변경할 수 있습니다.

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

특정 int 인덱스의 String str에서 문자를 삭제하는 경우:

    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 클래스의 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);
}

* String Builder 및 deletecharAt를 사용하여 문자열 값을 삭제할 수 있습니다.

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+""));   
  }
}

예. Java에서 문자열의 개별 문자, 즉 deleteCharAt를 제거하는 기능이 내장되어 있습니다.

예를들면,

public class StringBuilderExample 
{
   public static void main(String[] args) 
   {
      StringBuilder sb = new StringBuilder("helloworld");
      System.out.println("Before : " + sb);
      sb = sb.deleteCharAt(3);
      System.out.println("After : " + sb);
   }
}

산출량

Before : helloworld
After : heloworld

주어진 문자열에서 단일 문자를 삭제하려면 my method를 검색해 주세요.저는 str.replace All을 사용하여 문자열을 삭제해 왔습니다만, 이러한 방법은 지정된 문자열에서 문자를 삭제하는 여러 가지 방법이 있습니다만, 저는 replaceall 방식을 선호합니다.

문자 제거 코드:

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), "");
        }
    }


}

콘솔 이미지:

첨부된 콘솔 이미지를 찾아주세요.

여기에 이미지 설명 입력

물어봐줘서 고마워.:)

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

예를 들어 String에 있는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

반응형