gpt4 book ai didi

java - 提取第 n 个字符和另一个第 n 个字符之间的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 14:14:44 25 4
gpt4 key购买 nike

当我尝试将游戏的整个 map 加载到内存中时,它比我想要的要大一些。我正在尝试将 map 分成几 block 。我的游戏 map 是用逗号分隔的。 map 字符串的示例部分:“0, 0, 45, 32, 3, 3, 0, 0,”。

目前我正在使用以下方法,但大约需要 9 秒(我的 map 很大)。

String[] mapArr = map.split(", ");
short[] groundLayer = new short[chunkWidth * chunkHeight];
//code that fills in the groundLayer array

如果玩家在 1 个方向走得太远,游戏中的 9 秒等待将不起作用。

我的想法是做一些事情,将“映射字符串”从逗号(int firstComma)子串到逗号(int lastComma)。

firstComma = characterX + (characterY * mapWidth);
lastComma = firstComma + (chunkWidth * chunkHeight);

然后我将仅拆分 (", ") 得到的子字符串。从性能角度来说,这是一个好主意吗?

做这样的事情最有效的方法是什么?子字符串、正则表达式、indexOf,有什么不同吗?任何帮助将不胜感激。

<小时/>

编辑在下面提供更多上下文:

我的 map 由多个图层组成,我使用“平铺”来绘制/导出它们。这是我从文件中读取并将它们保存到短数组中的方法。我尝试只从字符 X 拆分到字符 Y,而不是拆分整个 map 字符串。

try {
String map = readFile("res/images/tiles/MyFirstMap-building-p.json");
String[] strArr = map.split(", ");

buildingLayer = new short[chunkWidth * chunkHeight];
short arrayIndex = 0;
for(short y = 0; y < chunkHeight; y++) {
for(short x = 0; x < chunkWidth; x++) {
//get the absolute position of the cell
short cellX = (short) (characterX + x - chunkWidth / 2);
short cellY = (short) (characterY + y - chunkHeight / 2);
if(cellX >= 0 && cellX < mapWidth && cellY >= 0 && cellY < mapHeight) { //within bounds
buildingLayer[arrayIndex] = Short.parseShort(strArr[cellX + (cellY * mapWidth)]);
} else { //out of bounds, put down a placeholder
buildingLayer[arrayIndex] = 0;
}
arrayIndex++;
}
}
} catch (IOException e) {
logger.fatal("ReadMapFile(building)", e);
JOptionPane.showMessageDialog(theDesktop, getStringChecked("message_file_locks") + "\n\n" + e.getMessage(), getStringChecked("message_error"), JOptionPane.ERROR_MESSAGE);
System.exit(1);
}


private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
return Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
}

最佳答案

这是我采用的解决方案(为了简单起见,我删除了很多循环逻辑)。感谢@Elliott Frisch 在评论中提供的帮助。

private static short[] scanMapFile(String path, int[] leftChunkSides, int[] rightChunkSides) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(path));
scanner.useDelimiter(", ");

short[] tmpMap = new short[chunkWidth * chunkHeight];
int count = 0;

while(scanner.hasNext()){
tmpMap[count] = scanner.nextShort();
count++;
}

scanner.close();
return tmpMap;
}

关于java - 提取第 n 个字符和另一个第 n 个字符之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27892554/

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