简体   繁体   English

从字符串中删除动态字符

[英]delete dynamic character from string

I have a string containing numbers separated with , .我有一个包含用,分隔的数字的字符串。 I want to remove the , before the first character.我想删除了,第一个字符之前。

The input is ,1,2,3,4,5,6,7,8,9,10 , and this code does not work:输入是,1,2,3,4,5,6,7,8,9,10 ,这段代码不起作用:

results.replaceFirst(",","");

Strings are immutable in Java.字符串在 Java 中是不可变的。 Calling a method on a string will not modify the string itself, but will instead return a new string .对字符串调用方法不会修改字符串本身,而是会返回一个新的字符串

In order to capture this new string, you need to assign the result of the operation back to a variable:为了捕获这个新字符串,您需要将操作的结果分配回一个变量:

results = results.replaceFirst(",", "");

Try this尝试这个

String str = ",1,2,3,4,5,6,7,8,9,10";
if(Objects.nonNull(str) && str.startsWith(",")){
  str = str.substring(1, str.length());
}

it will remove , at first position它会删除,在第一位置

you can also do like this ..你也可以这样做..

String str = ",1,2,3,4,5,6,7,8,9,10";
String stre = str.replaceFirst("^,", "");
Log.e("abd",stre);

Try this尝试这个

String str = ",1,2,3,4,5,6,7,8,9,10";
str = str .startsWith(",") ? str .substring(1) : str ;
System.out.println("output"+str);  // 1,2,3,4,5,6,7,8,9,10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM