Javaの部分文字列:'文字列インデックスの範囲
-
11-09-2019 - |
質問
私は推測している方が引っ越したこのエラーが文字列と部分文字列、 null
値とします。がんの ".length() > 0"
部を廃止する。
ここでは、Javaのスニペット:
if (itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0,38));
}
else {
pstmt2.setString(3, "_");
}
私はこのエラー:
java.lang.StringIndexOutOfBoundsException: String index out of range: 38
at java.lang.String.substring(Unknown Source)
at MASInsert2.itemimport(MASInsert2.java:192)
at MASInsert2.processRequest(MASInsert2.java:125)
at MASInsert2.doGet(MASInsert2.java:219)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:627)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:835)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:640)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1286)
at java.lang.Thread.run(Unknown Source)
解決
I "推測し、私はこのエラーを取得しています 文字列をしようとしているので、 null値をサブストリング。しかし、ではないだろう 」.LENGTH()> 0" の部分は排除します その問題?
いいえ、itemdescription.length()を呼び出すitemdescriptionがnullのときに、本質的に にヌルのメソッドを呼び出そうとするからである。
StringIndexOutOfBoundsExceptionをではなく、NullPointerExceptionが発生しないだろう 他人が示されているように、、StringIndexOutOfBoundsExceptionをitemdescriptionは、少なくとも38文字でないことを示します。あなたは、おそらく(私はあなたが切り捨てしたいと仮定して)両方の条件を扱いたいます:
final String value;
if (itemdescription == null || itemdescription.length() <= 0) {
value = "_";
} else if (itemdescription.length() <= 38) {
value = itemdescription;
} else {
value = itemdescription.substring(0, 38);
}
pstmt2.setString(3, value);
あなたが行う場合は、ユーティリティ機能のための良い場所になるかもしれないことをたくさん...
他のヒント
これはsubstring
が短い文字列を処理する方法に実装されていないのは残念ですパイソンます。
[OK]を、私たちは、代わりに、私はこの短いバリアントのために行くかどう-elseの節の、それを変更し、このエッジケースに我々はsubstr
を使用するたびに考慮することはできません
myText.substring(0, Math.min(6, myText.length()))
あなたは本当に、文字列の長さが38以上であるかどうかを確認する必要があります。
私は Apacheのコモンズのlang のをお勧めします。ワンライナーは、問題の世話をする。
pstmt2.setString(3, StringUtils.defaultIfEmpty(
StringUtils.subString(itemdescription,0, 38), "_"));
substring(0,38)
は、文字列が38文字以上であることを有することを意味します。ない場合は、「文字列のインデックスが範囲外です」。
if (itemdescription != null && itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38)));
} else {
pstmt2.setString(3, "_");
}
itemdescription
したいので、私は、あなたの列の長さが38個の文字であると仮定しています。次のような効用関数は、あなたが欲しいものを行う必要があります:
/**
* Truncates s to fit within len. If s is null, null is returned.
**/
public String truncate(String s, int len) {
if (s == null) return null;
return s.substring(0, Math.min(len, s.length()));
}
あなたがちょうどそうのようにそれを呼び出します
String value = "_";
if (itemdescription != null && itemdescription.length() > 0) {
value = truncate(itemdescription, 38);
}
pstmt2.setString(3, value);
Javaの substring
方法に失敗したときにしてみる部分文字列からのリターン-インデックスではのものより長い文字列になります。
簡単にインタビューを受けたことがある利用 Apache Commons StringUtils.substring
:
public static String substring(String str, int start)
Gets a substring from the specified String avoiding exceptions.
A negative start position can be used to start n characters from the end of the String.
A null String will return null. An empty ("") String will return "".
StringUtils.substring(null, *) = null
StringUtils.substring("", *) = ""
StringUtils.substring("abc", 0) = "abc"
StringUtils.substring("abc", 2) = "c"
StringUtils.substring("abc", 4) = ""
StringUtils.substring("abc", -2) = "bc"
StringUtils.substring("abc", -4) = "abc"
Parameters:
str - the String to get the substring from, may be null
start - the position to start from, negative means count back from the end of the String by this many characters
Returns:
substring from start position, null if null String input
ノートが使えない場合は、Apache Commons libにあることができ グラブの部品に必要なソースから
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start {@code n}
* characters from the end of the String.</p>
*
* <p>A {@code null} String will return {@code null}.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, {@code null} if null String input
*/
public static String substring(final String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
itemdescription
は38文字よりも短くなっています。どのStringOutOfBoundsException
がスローされている理由です。
.length() > 0
をチェックすると、単にString
はあなたが何をする必要があるか、いくつかの非NULL値は、長さが十分な長さであることを確認しているいるを確認します。あなたが試すことができます:
if(itemdescription.length() > 38)
...
あなたは文字列の長さを確認する必要があります。あなたがいる限り文字列substring(0,38)
ないようnull
を行うことができますことを前提としていますが、実際には、少なくとも38文字の長さにする文字列を必要とします。
これを適切に使っている 試合 の代わりに 部分文字列.
と 部分文字列:
if( myString.substring(1,17).equals("Someting I expect") ) {
// Do stuff
}
// Does NOT work if myString is too short
と 試合 (利用Regex表記):
if( myString.matches("Someting I expect.*") ) {
// Do stuff
}
// This works with all strings
取得する場合は、こitemdescriptionはより短い文字数全角38文字
ができる例外はスローされ、ときには、JAVA API き場合のための文字列#部分文字列(int,int): https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-int-
部分文字列 公文字列の部分文字列(int beginIndex,int endIndex) . . . 戻り値: IndexOutOfBoundsException if the beginIndex is negative, or endIndexより大きい長さのこのStringオブジェクト, or beginIndex is larger than endIndex. (same applies to previous java versions as well)