IT

특정 위치에서 문자열에 문자를 삽입하는 방법은 무엇입니까?

lottoking 2020. 6. 22. 07:30
반응형

특정 위치에서 문자열에 문자를 삽입하는 방법은 무엇입니까?


나는에 받고 있어요 int6 자리 값. String의 끝에서 2 자리의 소수점 (.) 으로 표시하고 싶습니다 int. 나는를 사용하고 싶어 float하지만 사용하도록 제안되었다 String(대신 더 나은 디스플레이 출력 1234.5될 것입니다 1234.50). 따라서 int매개 변수로 매개 변수 String를 사용하고 끝에서 소수점 2 자리로 올바르게 형식이 지정된 함수가 필요합니다 .

말하다:

int j= 123456 
Integer.toString(j); 

//processing...

//output : 1234.56

int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());

주석에서 언급했듯이 StringBuilder 는 아마도 StringBuffer를 사용하는 것보다 빠른 구현 일 것 입니다. Java 문서에서 언급했듯이 :

이 클래스는 StringBuffer와 호환되는 API를 제공하지만 동기화를 보장하지는 않습니다. 이 클래스는 문자열 버퍼가 단일 스레드에 의해 사용되는 장소에서 StringBuffer를 대체하는 대체물로 사용하도록 설계되었습니다 (일반적인 경우). 가능한 경우이 클래스는 대부분의 구현에서 더 빠를 것이기 때문에 StringBuffer에 우선하여 사용하는 것이 좋습니다.

사용법 :

String str = Integer.toString(j);
str = new StringBuilder(str).insert(str.length()-2, ".").toString();

또는 동기화가 필요한 경우 비슷한 사용법으로 StringBuffer 를 사용하십시오.

String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();

int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);

대부분의 유스 케이스에서 StringBuilder(이미 답변 된대로)를 사용하는 것이 좋은 방법입니다. 그러나 성능이 중요한 경우 이는 좋은 대안이 될 수 있습니다.

/**
 * Insert the 'insert' String at the index 'position' into the 'target' String.
 * 
 * ````
 * insertAt("AC", 0, "") -> "AC"
 * insertAt("AC", 1, "xxx") -> "AxxxC"
 * insertAt("AB", 2, "C") -> "ABC
 * ````
 */
public static String insertAt(final String target, final int position, final String insert) {
    final int targetLen = target.length();
    if (position < 0 || position > targetLen) {
        throw new IllegalArgumentException("position=" + position);
    }
    if (insert.isEmpty()) {
        return target;
    }
    if (position == 0) {
        return insert.concat(target);
    } else if (position == targetLen) {
        return target.concat(insert);
    }
    final int insertLen = insert.length();
    final char[] buffer = new char[targetLen + insertLen];
    target.getChars(0, position, buffer, 0);
    insert.getChars(0, insertLen, buffer, position);
    target.getChars(position, targetLen, buffer, position + insertLen);
    return new String(buffer);
}


당신은 사용할 수 있습니다

System.out.printf("%4.2f%n", ((float)12345)/100));

코멘트에 따르면, float 대신 double을 사용하는 것처럼 12345 / 100.0이 더 좋습니다.


ApacheCommons3 StringUtils를 사용하면 다음을 수행 할 수도 있습니다.

int j = 123456;
String s = Integer.toString(j);
int pos = s.length()-2;

s = StringUtils.overlay(s,".", pos, pos);

it's basically substring concatenation but shorter if you don't mind using libraries, or already depending on StringUtils


If you are using a system where float is expensive (e.g. no FPU) or not allowed (e.g. in accounting) you could use something like this:

    for (int i = 1; i < 100000; i *= 2) {
        String s = "00" + i;
        System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2));
    }

Otherwise the DecimalFormat is the better solution. (the StringBuilder variant above won't work with small numbers (<100)


  public static void main(String[] args) {
    char ch='m';
    String str="Hello",k=String.valueOf(ch),b,c;

    System.out.println(str);

    int index=3;
    b=str.substring(0,index-1 );
    c=str.substring(index-1,str.length());
    str=b+k+c;
}

I think a simpler and more elegant solution to insert a String in a certain position would be this one-liner:

target.replaceAll("^(.{" + position + "})", "$1" + insert);

For example, to insert a missing : into a time String:

"-0300".replaceAll("^(.{3})", "$1:");

What it does is, matches position characters from the beginning of the string, groups that, and replaces the group with itself ($1) followed by the insert string. Mind the replaceAll, even though there's always one occurrence, because the first parameter must be a regex.

Of course it does not have the same performance as the StringBuilder solution, but I believe the succinctness and elegance as a simple and easier to read one-liner (compared to a huge method) is sufficient for making it the preferred solution in most non performance-critical use-cases.

Note I'm solving the generic problem in the title for documentation reasons, of course if you are dealing with decimal numbers you should use the domain-specific solutions already proposed.


// Create given String and make with size 30
String str = "Hello How Are You";

// Creating StringBuffer Object for right padding
StringBuffer stringBufferRightPad = new StringBuffer(str);
while (stringBufferRightPad.length() < 30) {
    stringBufferRightPad.insert(stringBufferRightPad.length(), "*");
}

System.out.println("after Left padding : " + stringBufferRightPad);
System.out.println("after Left padding : " + stringBufferRightPad.toString());

// Creating StringBuffer Object for right padding
StringBuffer stringBufferLeftPad = new StringBuffer(str);
while (stringBufferLeftPad.length() < 30) {
    stringBufferLeftPad.insert(0, "*");
}
System.out.println("after Left padding : " + stringBufferLeftPad);
System.out.println("after Left padding : " + stringBufferLeftPad.toString());

Try this :

public String ConvertMessage(String content_sendout){

        //use unicode (004E00650077) need to change to hex (&#x004E&#x;0065&#x;0077;) first ;
        String resultcontent_sendout = "";
        int i = 4;
        int lengthwelcomemsg = content_sendout.length()/i;
        for(int nadd=0;nadd<lengthwelcomemsg;nadd++){
            if(nadd == 0){
                resultcontent_sendout = "&#x"+content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
            }else if(nadd == lengthwelcomemsg-1){
                resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";";
            }else{
                resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
            }
        }
        return resultcontent_sendout;
    }

참고 URL : https://stackoverflow.com/questions/5884353/how-to-insert-a-character-in-a-string-at-a-certain-position

반응형