Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

java - String index value access

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...