Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This problem is related to String and array in Java. Say I have a String S= abcd. I have an array index[]={2}. My problem is to find out the value from String S at its index position 2 because array index[] hold 2. I have a target array which contain "EF". Now if S contain a at position 2 then it will replaced by "EF".

How to access 2 position of S. Is it something like that. S[index[0]] Is this return S[2]?

Example: Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"] Output: "eeebffff" Explanation: "a" starts at index 0 in S, so it's replaced by "eee". "cd" starts at index 2 in S, so it's replaced by "ffff".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

Edited
After your comment, I added the sources array and assuming that both arrays sources and targets have the same length:

    String s = "abcd";
    String[] sources = {"a","cd"};
    int[] indexes  = {0, 2};
    String[] targets = {"eee", "ffff"};

    int more = 0;

    for (int i = 0; i < targets.length; i++) {
        int startIndex = more + indexes[i];
        int endIndex = more + indexes[i] + sources[i].length();
        if (startIndex < s.length() && endIndex <= s.length()) {
            String sBefore = s.substring(0, indexes[i] + more);
            String sAfter = s.substring(indexes[i] + sources[i].length() + more);
            if (sources[i].equals(s.substring(startIndex, endIndex))) {
                s = sBefore + targets[i] + sAfter;
                more += targets[i].length() - sources[i].length();
            }
        }
    }

    System.out.println(s);

will print

eeebffff

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...