在Java中,我有一个字符串:

Jamaica

我想删除字符串的第一个字符,然后返回amaica

我该怎么做呢?


当前回答

在Java中,只有当前导字符是某个特定字符时才删除前导字符

在删除字符之前,使用Java三元运算符快速检查字符是否存在。只有当前导字符存在时才删除它,如果传递一个空白字符串,则返回空白字符串。

String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

打印:

blankstring
foobar
moobar

Java,删除字符串中任意位置的所有字符实例:

String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"

Java,删除字符串中任意位置的字符的第一个实例:

String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"

其他回答

substring()方法返回一个新的String,其中包含当前包含在该序列中的字符的子序列。

子字符串从指定的开头开始,扩展到索引末尾的字符- 1。

它有两种形式。首先是

字符串子字符串(int FirstIndex)

这里,FirstIndex指定子字符串所在的索引 开始。此表单返回以。开始的子字符串的副本 FirstIndex并运行到调用字符串的末尾。

String子字符串(int FirstIndex, int endIndex)

这里,FirstIndex指定开始索引,endIndex指定 停止点。返回的字符串包含所有的字符 从开始索引到结束索引,但不包括结束索引。

例子

   String str = "Amiyo";
   // prints substring from index 3
   System.out.println("substring is = " + str.substring(3)); // Output 'yo'

使用substring()并给出要从前面修剪的字符数。

String value = "Jamaica";
value = value.substring(1);

答:“amaica”

另一个解决方案,你可以使用replaceAll和一些regex ^来解决你的问题。{1}(正则表达式演示)为例:

String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica

在Java中,只有当前导字符是某个特定字符时才删除前导字符

在删除字符之前,使用Java三元运算符快速检查字符是否存在。只有当前导字符存在时才删除它,如果传递一个空白字符串,则返回空白字符串。

String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

打印:

blankstring
foobar
moobar

Java,删除字符串中任意位置的所有字符实例:

String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"

Java,删除字符串中任意位置的字符的第一个实例:

String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"

The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.

这对性能有许多影响。每次你“修改”一个字符串,你实际上是在创建一个新的字符串,所有的开销(内存分配和垃圾收集)。因此,如果你想对一个字符串进行一系列的修改,并且只关心最终的结果(一旦你“修改”了中间的字符串,它们就会死),那么使用StringBuilder或StringBuffer可能更有意义。