gpt4 book ai didi

java - 在不使用任何字符串函数的情况下从java中的字符串创建子字符串

转载 作者:行者123 更新时间:2023-11-29 07:05:18 25 4
gpt4 key购买 nike

我最近在一次面试中被问到这个问题(3+ 经验)。不允许包含 String.length 的字符串函数。我有 5 分钟的时间来编写完整的代码。

示例

String ="abcfedbca"
subString = "fed"

实际上,我请他详细说明一下,他说“Java 实现很简单,我应该详细说明什么”,基于这个问题,他只说我的核心 Java 非常薄弱。

最佳答案

请注意,您的问题不是很准确,因此您的要求不是很清楚。

简单的方法:

String st = new StringBuilder(s).substring(3,6); 

或者你可以直接构造新的String,使用反射获取char数组:

public static String substring(String s, int from, int to){
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
char [] tab = (char[])f.get(s);
f.setAccessible(false);
return new String(tab, from, to - from);
}


这些也可以是选项(请注意,它仅在原始 String 适合十六进制格式时才有效):

String s ="abcfedbca";
BigInteger bi = new BigInteger(s, 16);
bi = bi.and(new BigInteger("16699392")); //0xfed000 in hexa
bi = bi.shiftRight(12);
System.out.println(bi.toString(16));

或者更简单:

String s ="abcfedbca";
System.out.println(Integer.toHexString((int)(Long.parseLong(s, 16) & 16699392) >> 12));

如果你想要一个更通用的方法,这个可能适合你的情况:

public static void main(String [] args){
String s ="abcfedbca";
System.out.println(substring(s, 2, 5, 9));
}

public static String substring (String s, int from, int to, int length){
long shiftLeft = 0;
long shiftRight = (length - to - 1) * 4;
for(int i = 0; i < to - from - 1; i++){
shiftLeft += 15;
shiftLeft = shiftLeft << 4;
}
shiftLeft += 15;
return Long.toHexString((Long.parseLong(s, 16) & (shiftLeft << shiftRight)) >> shiftRight);
}

关于java - 在不使用任何字符串函数的情况下从java中的字符串创建子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20529580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com