简体   繁体   English

Java字符串替换问题

[英]Java String replace issue

I have a code in which I am using replace method on Java String, but it is not working.. Please point out the mistake.. 我有一个在Java String上使用replace方法的代码,但是它不起作用..请指出错误。

static String[] cavityMap(String[] grid) {
    String[] ans = grid;
    for(int i = 1; i<= grid.length-2; i++){
        for(int j = 1; j<= grid[i].length()-2; j++){
            int e = Integer.parseInt(grid[i].charAt(j) + "");
            int t = Integer.parseInt(grid[i - 1].charAt(j) + "");
            int b = Integer.parseInt(grid[i + 1].charAt(j) + "");
            int l = Integer.parseInt(grid[i].charAt(j - 1) + "");
            int r = Integer.parseInt(grid[i].charAt(j + 1) + "");
        if(e > t && e > b && e > l && e > r){
            ans[i] = ans[i].replace("X",(ans[i].charAt(j) + ""));
            System.out.println(ans[i].replace("X",(ans[i].charAt(j) + "")));
        }
        }    
   }    
   return ans;
}

The code execution is going in if conditional part.. But it is printing the same value as before.. Why is it not replacing the String with "X".. Thanks in advance 如果有条件的话,代码执行会进入..但是它打印的值与以前相同。.为什么它不将字符串替换为“ X”。

ans[i].replace("X",(ans[i].charAt(j) + ""))

will replace all occurences of "X" with ans[i].charAt(j) + "" . 将用ans[i].charAt(j) + ""替换所有出现的"X" ans[i].charAt(j) + ""

If your intention is to replace ans[i].charAt(j) + "" with "X" you will need to swap your params: 如果您打算将ans[i].charAt(j) + ""替换为"X" ,则需要交换参数:

ans[i].replace((ans[i].charAt(j) + ""), "X")

Also, using concatenation with empty string to cause conversion from char to String is discouraged. 另外,不建议使用空字符串的连接来引起从charString转换。 Consider explicitly invoking Character.toString or String.valueOf 考虑显式调用Character.toStringString.valueOf

ans[i].replace(String.valueOf(ans[i].charAt(j)), "X")

or better yet, since your replacement is a single char , just work in that type 或更好的是,由于您的替换项是单个char ,因此只能使用该类型

ans[i].replace(ans[i].charAt(j), 'X')

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

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