检查char的某些索引位置

时间:2015-02-14 09:30:56

标签: java if-statement

    Scanner keyboard = new Scanner (System.in);
   String str = keyboard.next();

   int strlen = str.length();
   //char lastchar = str.charAt(strlen - 1);
   char lastchar2 = str.charAt(strlen - 2);
   if (lastchar2 = 'l'){
   System.out.print("L is in that position");}

我想知道如何检查某个索引是否是if语句中的某个字母,谢谢

2 个答案:

答案 0 :(得分:0)

而不是

if (lastchar2 = "l"){

使用

if (lastchar2 == 'l'){ //single quotes as we represent String literals with double quotes and "==" since we use "=" as an assignment operator and not for comparison.

请注意:您可能需要验证输入字符串(str)中是否包含至少两个字符。

答案 1 :(得分:0)

测试给定索引处的char:

if (str.charAt(i) == 'x')

您也可以考虑:

if (str.endsWith("l"))