如何在Android中使用replace替换字符串中的单词?

时间:2014-08-20 08:32:18

标签: android string

我想使用substring替换String中的一个单词。但它看起来没有用。

例如:string is 0000,我想将第一个字从0替换为1. 它应该是1000。但事实并非如此。

代码如下所示

String WorkStatus = "0000";
if(WorkStatus.substring(0, 1).matches("0"))
{
    WorkStatus.substring(0, 1).replace("0", "1");
    Log.d(TAG, "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
    Log.d(TAG, "WorkStatus = " + WorkStatus + "\n");
}

它没有用,字符串总是显示0000.而我想要的是“1000”

我错过了什么吗?

4 个答案:

答案 0 :(得分:4)

使用此

String WorkStatus = "0000";
//You use matches, while you might as well use equals
if (WorkStatus.substring(0, 1).equals("0")) { 
    //reassign workstatus to workstatus where the first entry is a '1' + the last three chars "000"
    WorkStatus = WorkStatus.substring(0, 1).replace("0", "1") + WorkStatus.substring(1, WorkStatus.length()); 
    Log.d(TAG, "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
    Log.d(TAG, "WorkStatus = " + WorkStatus + "\n");
}

您没有将修改后的字符串分配给WorkStatus

另一种可能性是将字符串转换为char[]并替换索引,而不是使用子字符串。

String WorkStatus = "0000";
char[] chars = WorkStatus.toCharArray();
if (chars[0] == '0') {
    chars[0] = '1';
    WorkStatus = new String(chars);
}

如果您希望其他字符变为1而不是零,请将chars[0]更改为chars[index],其中index是您要从0更改为1的索引

或者,更简单一点,使用StringBuilder

int yourIndex = 2; //your index which you want to check for 0 and change to 1
StringBuilder sb = new StringBuilder("0000");
if (sb.charAt(yourIndex) == '0')
    sb.setCharAt(yourIndex, '1');
WorkStatus = sb.toString();

答案 1 :(得分:1)

方法替换在替换后具有返回值 你shuold将结果辞职给String

  

WorkStatus = WorkStatus.substring(0,1).replace(" 0"," 1")+ WorkStatus.substring(1,WorkStatus.length();

答案 2 :(得分:0)

WorkStatus.substring(0, 1).replace("0", "1");返回1,您应该使用StringBuilder代替String

我的解决方案:

StringBuilder WorkStatus = new StringBuilder("0000");
int pos = WorkStatus.indexOf("0", 0);
if (pos != -1) {
    WorkStatus.replace(pos, pos + 1, "1");
}
System.out.print(WorkStatus);

答案 3 :(得分:0)

如果您将其分配给新变量(如下面的代码),则可以获得所需的内容。

String newWorkStatus=WorkStatus.substring(0, 1).replace("0", "1")+WorkStatus.substring(1);
                  Log.d("LOG", "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
                  Log.d("LOG", "WorkStatus = " + WorkStatus + "\n");
                  Log.d("LOG", "New WorkStatus = " + newWorkStatus + "\n");