简体   繁体   English

根据偏移和计数修剪字符串

[英]Trim String based on Offset and Count

Is there an easy way to trim a String based on his Offset and Count values, that is, a function that returns OO for a String FOOBAR with an offset of 1 and a count of 2? 是否有一种简单的方法可以根据其偏移量和计数值来修剪字符串,也就是说,该函数为offset为1且count为2的字符串FOOBAR返回OO

Obvious, one could write a simple function for this task, but I wonder if their is not a predefined Java functionality for this? 显然,可以为此任务编写一个简单的函数,但是我想知道它们是否不是为此目的预定义的Java功能?

//edit: To clearify: I do mean the offset and count values defined within the given String , not external Integer values. // edit:澄清一下:我的意思是在给定String定义的offsetcount数值,而不是外部Integer值。

EDIT: Okay, now you've made your question clearer, it sounds like this is the scenario you're talking about, and the solution using the String(String) constructor: 编辑:好的,现在您已经使问题更清楚了,听起来这就是您正在谈论的场景,以及使用String(String)构造函数的解决方案:

// offset = 0, count = 6, backing array = { 'F', 'O', 'O', 'B', 'A', 'R' }
String original = "FOOBAR";

// offset = 1, count = 2, backing array = { 'F', 'O', 'O', 'B', 'A', 'R' }
String substring = original.substring(2);

// offset = 0, count = 2, backing array = { 'O', 'O' }
String trimmed = new String(substring);

Yup, substring : 是的, substring

String substring = text.substring(offset, offset + count);

substring takes two parameters - the "begin index" (inclusive) and the "end index" (exclusive) - hence the addition in the above code. substring具有两个参数-“ begin index”(包含)和“ end index”(不含)-因此在上面的代码中添加了参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM