Java中字符串字符的结尾

End of string character in Java(Java中字符串字符的结尾)
本文介绍了Java中字符串字符的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在解决一个简单的问题:

I was solving an easy question :

在Java中删除字符数组的某些字符,想法很简单:

Remove certain characters of a character array in Java , the idea is straightforward :

static void remove_char(char[] arr, char c){
    int r = 0;
    for (int i = 0 ; i < arr.length ; i++){
        if (arr[i] == c){
            r++;
            continue;
        }
        arr[i - r] = arr[i];
    }
    arr[arr.length - r] = ''; // ??
    return;
}

我想放置一个 结束字符,它表示当我们想要生成字符串时不必考虑数组的其余部分,例如,使用 new String(arr)

I want to put an ending character which signals that the rest of the array doesn't have to be considered when we want to, for example, generate a string using new String(arr)

Java 中有这样的字符吗?(我猜在 C 中是 但我不确定)

Is there any such character in Java ? ( I guess in C it's but I am not sure)

例如当我们调用:

System.out.println(new String(remove_char(new char[] {'s','a','l','a','m'} ,'a')))

这将被打印出来:slm m

虽然我想获得 slm 并且我想 in-place 不使用新数组

While I want to get slm and I want to do this in-place not using a new array

推荐答案

Java 不像 C 那样标记"字符串的结尾.它跟踪长度和值,因此字符串中可能包含零字符 ().如果您从包含 字符的 char 数组创建 String,则生成的 String 将包含这些字符.

Java doesn't "mark" the end-of-string as C does. It tracks length & values, so it's possible to have zero-chars () in the string. If you create a String from a char array containing chars, the resultant String will contain those characters.

另请注意,数组具有静态大小 - 它不能重新调整大小,因此您必须自己跟踪大小"(String 构造函数不会从 char 末尾为您删除不需要的字符数组).

Note also, an array has a static size - it cannot be re-sized, so you'll have to track the "size" yourself (the String constructor won't drop undesirable characters for you from the end of a char array).

考虑使用任一:

  • Clyde Byrd III 建议的 StringBuilder,或

String(char value[], int offset, int count);您必须以编程方式确定 offsetcount 的适当值.也许字符串方法,例如 replaceconcatsubstring 可能会有所帮助.

String(char value[], int offset, int count); you'll have to determine programmatically what the appropriate values for offset and count would be. Perhaps String methods, such as replace, concat, or substring might help.

这篇关于Java中字符串字符的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)