字符串之从规定的字符串中根据下标得到字符

113 阅读1分钟

题目:

例如给规定字符串str = "a_3_b_4_c_5",给定下标4,会得到字符'b'

str = "a_3_b_4_c_5" 就意味着字符串是str = "aaabbbbccccc";

然后下标4,就会得到字符‘b’

代码实现:

package com.chenyu.string.cn;

import java.util.Arrays;


public class GetCharInString {
	
	public static String target = "a_3_b_4_c_8";
	public static void main(String[] args) {
		char result = getCharInString(target, 8);
		System.out.print("result:" + result);
	}
	
	//方法一 先分割 再拼接 再获取
	public static char getCharInString(String target, int index) {
		if (target == null || target == "") {
			return 0;
		} 
		if (index < 0) {
			return 0;
		}
		String[] targets = target.split("_");
		String result = "";
		for (int i = 0; i < targets.length; ++i) {
			if (i % 2 == 0) {
				result += getStringByAcount(targ