0

I have an alphabet which I want to replace before any alphabet rather than the after. For example if I have a word "instant" I want to make sure that char 'a' after the 't' should be before the 't'. It should be insatnt. Wherever any of the word has an 'a' it should be replaced before but not after. Is there any possible way out of this?

4

3 回答 3

1

您只给出了一个示例,因此我无法发布一般性答案。也许你可以概括它:

String input = "instant";
String replaced = input.replaceAll("(\\w)a", "a$1");
于 2013-07-30T13:35:04.960 回答
1

你可以使用正则表达式来做你想做的事。

在一般情况下,您要替换<something>aa<something>where<something>是单个字符,任何字符。

在正则表达式中,这将替换(\\w)aa$1,即查找 ana前面有某事并捕获该某事的情况。a然后用捕获的东西替换它:

public static void main(String[] args) throws Exception {
    final String s = "instant";
    System.out.println(s.replaceAll("(\\w)a", "a$1"));
}

输出:

insatnt
于 2013-07-30T13:36:10.900 回答
0

老式的方法如下:

char reference_char = 'a';
String old_string = "instant";

char[] test_array = old_string.toCharArray();        
int i = 0;

for (char c : test_array) {
    if (i > 0) {
        if (c == reference_char) {
            test_array[i] = test_array[i - 1];
            test_array[i - 1] = reference_char;
        }
    }
    ++i;
}

String new_string =  new String(test_array);
System.out.println(new_string);

我希望我理解你的问题。

一切顺利!

于 2013-07-30T14:04:50.347 回答