字符串索引值访问

String index value access

此问题与Java中的字符串和数组有关。假设我有一个 String S= abcd。我有一个数组 index[]={2}。我的问题是从 String S 的索引位置 2 中找出值,因为数组索引 [] 为 2。我有一个包含 "EF" 的目标数组。现在,如果 S 在位置 2 包含 a,那么它将被 "EF" 替换。

如何访问S的2个位置。是不是这样的。 S[index[0]] 这是 return S[2] 吗?

示例: 输入:S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"] 输出:"eeebffff" 解释:"a" 从 S 中的索引 0 开始,因此它被 "eee" 取代。 "cd" 从 S 中的索引 2 开始,因此它被替换为 "ffff"。

已编辑
在您发表评论后,我添加了 sources 数组并假设数组 sourcestargets 具有相同的长度:

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

将打印

eeebffff

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

S.charAt(2) returns 索引 2 处的 char 值,或者您可以 char[] charArray=S.toCharArray() 获取 char[] 并在数组索引中访问它就像 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();
}

如果您确定只能存在一个a

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