Java Substring : 'String Index Out Out Out Out'
-
11-09-2019 - |
문제
문자열이 구하기를 시도하기 때문에이 오류가 발생한다고 생각합니다. null
값. 그러나 그렇지 않을 것입니다 ".length() > 0"
부분이 그 문제를 제거합니까?
자바 스 니펫은 다음과 같습니다.
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)
해결책
나는 문자열이 널 값을 기판하려고하기 때문에이 오류를 받고 있다고 생각합니다. 그러나 ".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
다른 언어와 같이 짧은 문자열을 처리하는 방식으로 구현되지 않습니다.
좋아, 우리는 그것을 바꿀 수없고 우리가 사용할 때 마다이 엣지 케이스를 고려해야합니다. substr
, IF-ELSE 조항 대신에 나는이 짧은 변형을 갈 것입니다.
myText.substring(0, Math.min(6, myText.length()))
문자열의 길이가 38에 더 크거나 같은지 확인해야합니다.
추천합니다 Apache Commons 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, "_");
}
당신의 열은 길이 38 자라고 가정합니다. 잘라 itemdescription
데이터베이스에 맞습니다. 다음과 같은 유틸리티 기능은 원하는대로해야합니다.
/**
* 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 's substring
문자열보다 긴 인덱스에서 시작하는 하위 문자열을 시도 할 때 메소드가 실패합니다.
쉬운 대안은 사용하는 것입니다 아파치 커먼즈 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
널 값이없는 값이 있습니다. 길이가 충분히 길어야하는지 확인하는 것입니다. 당신은 시도 할 수 있습니다 :
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 자 미만이면 이것을 얻을 수 있습니다.
String#substring (int, int)의 경우에 어떤 예외가 발생하고 Java API에있을 때를 볼 수 있습니다. https://docs.oracle.com/javase/9/docs/api/java/lang/string.html#substring-int-int-int-
서브 스트링 public String substring (int beginindex, int endindex) . . . 던지기 : indexoutofBoundSexection if the beginIndex is negative, or endindex는이 문자열 객체의 길이보다 큽니다., or beginIndex is larger than endIndex. (same applies to previous java versions as well)