简体   繁体   English

如何写一个函数布尔成功(char a,char b,String s)? 使用s.equals(“”),s.charAt(0),s.substring(1)

[英]How can I write a function boolean succeeds(char a, char b, String s)? using s.equals(“”), s.charAt(0), s.substring(1)

I am trying to write a function that takes a string s and returns true if every occurrence of the character b is always succeeded by the character a, and false otherwise. 我正在尝试编写一个带字符串s的函数,如果字符b的每次出现总是由字符a继承,则返回true,否则返回false。 I have tried: 我努力了:

boolean succeeds(char a, char b, String s) {
    boolean to_return = true;
    boolean seen_a = false;
    while(true) {
        if (s.equals("")) return to_return;
            char c2 = s.charAt(0);
            if (c2 == a) seen_a = true;
            if (c2 == b) {
                if (!seen_a) return false;
            }
            s = s.substring(1);
        }
    }
}

I think I have the right idea. 我想我有正确的想法。 But I don't know how to put it together. 但我不知道怎么把它放在一起。

Given the guidelines, you can do something along the lines of 根据指南,你可以做一些事情

while (!s.equals("")) {
    char c = s.charAt(0);  // record first char
    s = s.substring(1);    // cut off first char


    // if "first char is 'b' and next is
    // not 'a'", we can return false
    if (c == b && (s.equals("") || s.charAt(0) != a))
        return false;                
}

return true;

By the way, this can be done much more easily: 顺便说一句,这可以更容易地完成:

return s.replace(""+b+a, "").indexOf(b) < 0;

(I just noticed that this approach was originally outlined in @JosephMyers' answer ) (我刚才注意到这种方法最初是在@JosephMyers的回答中概述的)

This sounds like homework, so it's probably your responsibility to work out the details, but several suggestions keep coming to my mind, anyway. 这听起来像是家庭作业,所以你可能有责任弄清楚细节,但无论如何,我仍然会想到一些建议。

For instance, you could try: 例如,您可以尝试:

  1. Remove all occurrences of "ba" in a temporary string. 删除临时字符串中出现的所有“ba”。
  2. If no other letter(s) "b" remain in the temporary string, then return true . 如果临时字符串中没有其他字母“b”,则返回true
  3. Otherwise return false . 否则返回false

Hints: You can use the replace method in step 1 and indexOf in step 2. (Click the links for tutorials/instructions You should be able to do this in two or three lines of code, depending on whether you use a ternary operator for the return value.) 提示:您可以使用步骤1中的replace方法和步骤2中的indexOf 。(单击教程/说明的链接您应该能够在两行或三行代码中执行此操作,具体取决于您是否使用三元运算符返回值。)

It need not be so complex. 它不需要那么复杂。 For example: 例如:

for (i = 0; i < s.length - 1; i++) {
  if (s.charAt(i - 1) == b && s.charAt(i) != a) {
    return false;
  }
}
return !s.endsWith(String.valueOf(b));

Assuming you're limited to the functions you put in the title, and that you want to check if every b is followed by a (and not the other way around): you're halfway there, but your logic is a bit backwards. 假设你只限于你在标题中输入的函数,并且你想要检查每个b后面是否有一个(而不是相反):你已经到了一半,但你的逻辑有点倒退。 When you're going through the string: 当你浏览字符串时:

(1) When you see "b", you will need to remember that fact. (1)当你看到“b”时,你需要记住这个事实。 So you probably want a variable seen_b instead of seen_a. 所以你可能想要一个变量seen_b而不是seen_a。

(2) On the next character, if you remember that you just saw "b", you then need to make sure the next character is "a". (2)在下一个角色上,如果你还记得你刚刚看到“b”,那么你需要确保下一个角色是“a”。 So instead of 而不是

if (c2 == b) {
    if (!seen_a) return false;
}

you probably should have something like 你应该有类似的东西

if (seen_b) {
    if (c2 != a) return false;
}

or more concisely 或者更简洁

if (seen_b && c2 != a) return false;

(3) Since seen_b==true means that the last character you saw is b, make sure you set it back to false every time you see something that isn't b. (3)因为seen_b == true表示你看到的最后一个字符是b,所以每次看到不是b的东西时,请确保将其设置为false。

(4) Make sure you do things right when the last character of the string is b. (4)确保在字符串的最后一个字符为b时正确执行操作。 You have to return false because this isn't followed by "a". 你必须返回false,因为这不是“a”。

Something like this should work. 这样的事情应该有效。 I have not compiled this. 我没有编译这个。 Hopefully it gets you in the right direction, even with possible syntax errors. 希望它能让您朝着正确的方向前进,即使可能存在语法错误。

public boolean succeeds(char a, char b, String s){
    boolean sawFirst= false;
    for(int i=0;i<s.length();i++){
        if(!sawA){
            if(s.charAt(i)==b)
                sawFirst = true;
        }
        else{
            if(s.charAt(i)!=a)
                return false;
            else sawFirst= false;
        }
    }
    return true;
}

using s.equals(“”), s.charAt(0), s.substring(1) ? 使用s.equals(“”),s.charAt(0),s.substring(1)?

how about this: 这个怎么样:

public static boolean succeeds(final char a, final char b, String s)
{
if(s==null||s.equals(""))
  return true;
char previousFirstChar,newFirstChar;
previousFirstChar=s.charAt(0);
while(true)
  {
  s=s.substring(1);
  if(s.equals(""))
     {
     if(previousFirstChar==b)
       return false;
     break;
     }
  newFirstChar=s.charAt(0);
  if(previousFirstChar==b && newFirstChar!=a))
    return false;
  previousFirstChar=newFirstChar;
  }
return true;
}

Looking at your title, I'm unclear if you mean you have to use s.equals, .charAt, and .substring. 看看你的标题,我不清楚你是否意味着你必须使用s.equals,.charAt和.substring。 However, if not, you can use a regular expression .*b[^a].*|.*b$ (thank you ajb ) for this, where the function fails if it matches b followed by any character but a (or the special case b at the end of the string), eg: 但是,如果没有,你可以使用正则表达式.*b[^a].*|.*b$ (谢谢你ajb ),如果它匹配b后跟任何字符但是a (或者字符串末尾的特殊情况b ),例如:

import java.util.regex.Pattern; 
...

public boolean succeeds (char a, char b, String s) {

    String quoteda = Pattern.quote(Character.toString(a));
    String quotedb = Pattern.quote(Character.toString(b));
    return !(s.matches(".*" + quotedb + "[^" + quoteda + "].*|.*" + quotedb + "$"));

}

Note that this will return true if the string doesn't contain a at all. 请注意,如果字符串不包含这将返回true, a都没有。 If you want it to return false in that case, you'd have to check first: 如果你希望它在这种情况下返回false,你必须先检查:

public boolean succeeds (char a, char b, String s) {

    if (s.indexOf(b) == -1)
        return false;

    String quoteda = Pattern.quote(Character.toString(a));
    String quotedb = Pattern.quote(Character.toString(b));
    return !(s.matches(".*" + quotedb + "[^" + quoteda + "].*|.*" + quotedb + "$"));

}

The reason we use Pattern.quote is to allow it to handle characters with special meaning in regular expressions, eg ']'. 我们使用Pattern.quote的原因是允许它处理正则表达式中具有特殊含义的字符,例如']'。

If you can't use regular expressions, a state-machine style approach will give you good results: 如果你不能使用正则表达式,状态机风格的方法会给你很好的结果:

public boolean succeeds (char a, char b, String s) {

    int state = 0;

    for (int n = 0; n < s.length(); ++ n) {
        if (state == 0) {
            if (s.charAt(n) == b)
                state = 1;
        } else if (state == 1) {
            if (s.charAt(n) == a)
                state = 0;
            else
                return false;
        }
    }

    return (state == 0);

}

Since there's only two states you could just use a boolean. 由于只有两个状态,你可以使用布尔值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写函数字符串替换(char a,char b,string s),用b替换字符串s中每次出现的字符a - how can I write a function string replace (char a , char b, string s) that replace each occurrence of the character a in the string s by b 从&#39;a&#39;||简化s.charAt &#39;b&#39;|| &#39;c&#39;|| 到一个s.charAt - Simplify s.charAt from 'a' || 'b' || 'c' || to one s.charAt 使用 String.valueOf(s.charAt(i)) 从 ArrayList 中删除 - Removing from ArrayList using String.valueOf(s.charAt(i)) Java,mask [s.charAt(i)]是什么意思? mask是一个布尔数组 - Java, what does mask[s.charAt(i)] mean? mask is a boolean array ++array[s.charAt(i) - &#39;A&#39;] 究竟做了什么? - What exactly does ++array[s.charAt(i) - 'A'] do? whats (s.charAt(low) != s.charAt(high)) {&quot; and &quot; int high = s.length() - 1; - whats (s.charAt(low) != s.charAt(high)) {" and " int high = s.length() - 1; 在使用“ addTextChangedListener”和“ Character.isLetterOrDigit(s.charAt(i))”收听时如何启用文本 - How to enable text when listening with “addTextChangedListener” and “Character.isLetterOrDigit(s.charAt(i))” s.equals(“”)和“”.equals(s)之间有什么区别 - What is the difference between s.equals(“”) and “”.equals(s) 从字符串中删除最后一个字母 s = s.substring(0, s.length()-1); + setText 仅有时有效 - Removing last letter from string s = s.substring(0, s.length()-1); + setText works only sometimes 我正在尝试从定义的字符串中删除字符串中的字符。 错误出现在这里:if(s.charAt(x)== punct.charAt(y)) - I am trying to remove characters in a string from a defined string. the error comes here: if(s.charAt(x) == punct.charAt(y))
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM