String index value access

2019-09-20 12:58发布

问题:

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".

回答1:

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


回答2:

My problem is to find out the value from String S at its index position 2

S.charAt(2) returns a char value at its index 2, or you can char[] charArray=S.toCharArray() to get a char[] and visit it in the array index way like charArray[2]

if S contain a at position 2 then it will replaced by "EF".

if(S.charAt(2)=='a'){
   StringBuilder sb=new StringBuilder(S);
   S=sb.replace(2,3,"EF").toString();
}

if you are sure that only one a can exists:

if(S.charAt(2)=='a'){
     S=S.replace("a","EF");
}