String index value access

天涯浪子 提交于 2019-12-13 08:28:43

问题


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");
}


来源:https://stackoverflow.com/questions/53992165/string-index-value-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!