字符串索引值访问 [英] String index value access

查看:85
本文介绍了字符串索引值访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何访问S的2个位置.类似吗? S [index [0]] 这是返回S [2]吗?

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

示例:输入:S ="abcd",索引= [0,2],源= ["a","cd"],目标= ["eee","ffff"]输出:"eeebffff"说明:"a"从S中的索引0开始,因此被"eee"代替."cd"从S的索引2开始,因此被"ffff"代替.

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

推荐答案

已编辑
在您发表评论之后,我添加了 sources 数组,并假设两个数组 sources targets 的长度相同:

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

将打印

eeebffff

这篇关于字符串索引值访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆