将字符串中的字符与字母进行比较? [英] Compare a character in a string with a letter?
问题描述
我想将字符串中的字符与字母"R"进行比较.因此,我想检查字符串中 i
位置上的字符是"R","L"还是"F".
I want to compare a character in a string with the letter "R". So I want to check if the character on the position i
in the string is a "R", a "L" or a "F".
这是我的代码,但是没有字...我是Java的初学者,对于提高我的代码并使之起作用的每一个想法都很满意.
This is my code, but it doesn't word... I'm a Java beginner and really happy about every idea to improve my code and makes it work.
for (int i = s.length()-2; i >= 0; i--){
if (s.charAt(i) == "R"){
s = s + "L";}
else if (s.charAt(i) == L){
s = s + "R";}
else {s = s + "F";}
//s = s + s.charAt(i);}//对于
// s = s + s.charAt(i); }//for
顺便说一句,完整的练习是获得一个随机字符串(例如RFFLF),添加一个R,然后以转后的顺序添加给定的字符串,并用L替换(在添加的字符串中)每个R和每个带有R的L.
By the way, the complete exercise is to get a random string (for example RFFLF), to add a R and then to add the given string in the turned around order and replace (in the added string) every R with L and every L with R.
推荐答案
首先,您必须小心自己的类型. s.charAt(i)
返回一个 char
类型(鉴于方法的名称,这并不奇怪),但是您正在将其与 String 进行比较.代码>
"R"
.那将无法编译,即使编译成功,也将无法正常工作.字符和字符串是不同的野兽,并且永远不相等.
First off, you must be careful with your types. s.charAt(i)
returns a char
type (not that surprising given the name of the method), but you're comparing it with a String
"R"
. That won't compile and even if it did, it wouldn't work; chars and String are different beasts and are never equal.
char
文字由单引号分隔,例如'R'
.
char
literals are delimited by single quotes, eg 'R'
.
此代码是我认为您要绑定的代码:
This code is what I think you're tying to code:
String result = "";
if (s.charAt(i) == 'R') {
result = result + "L"; // you could code + 'L' too - both will work
}
请注意,您尝试修改原始String也不起作用.根据我的代码使用新的字符串.更容易理解和正确处理.
Note that your attempt at modifying the original String won't work either. Use a new String as per my code. Much easier to understand and get right.
这篇关于将字符串中的字符与字母进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!