문자열이 회문인지 확인하기 위해 다음 프로그램을 발견했습니다. 코더 s.length()-1
에 루프 변수를 i
를 초기화하는 이유왜 문자열 길이가 -1
import java.util.Scanner;
public class PalindromeString{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the string which you want to check whether that is palindrome or not: ");
String s = in.next();
String r = "";
for(int i=s.length()-1; i>=0; i--){
r = r+s.charAt(i);
}
System.out.println("Reverse of entered string "+s+" is "+r);
if(r.equals(s)){
System.out.println("String "+s+" is palindrome.");
}else{
System.out.println("String "+s+" is not palindrome.");
}
}
}
나는 이해하지 못했다. 아무도 그 이유를 설명 할 수 있습니까? 문자열 길이에 대한 관련 콘텐츠를 검색했지만 이에 대한 대답을 찾을 수 없습니다.
변수 i가 인덱스로 사용되고 java의 인덱스가 0부터 시작하기 때문에 '-1'이 실행되지 않으면 for 루프의 첫 번째 명령문은 's.charAt (s.length())'가 존재하지 않기 때문에 에러가 발생했습니다 - 이것을 확인하십시오. 이것은 0 기반 인덱스를 사용하는 대부분의 언어에서 중요한 이해입니다. – hbogert
[substring()의 endIndex에서 1을 뺀 이유]의 가능한 복제본 (http://stackoverflow.com/questions/13781907/reason-for-subtracting-substrings-endindex-by-1) – Burkely91