在Javascript中检查字符串中的符号 [英] Checking symbols in string in Javascript

查看:81
本文介绍了在Javascript中检查字符串中的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在coderbyte上遇到问题,问题如下:


使用JavaScript语言,函数 SimpleSymbols(str)
获取传递的 str 参数并确定它是否是
可接受的序列返回字符串 true false
str 参数将由 + = 符号之间有几个字母
(即 ++ d + === + c ++ == a ),字符串为 true 每个
字母必须包含 + 符号。所以左边的字符串
将是 false 。该字符串不会为空,并且至少有
一个字母。


我写的代码是这样的:

  var SimpleSymbols = function(str){
var alpha = / [A-Za-z] /;
var symbolarr = str.split();
for(var i = 0; i< symbolarr.length; i ++){
if(alpha.test(symbolarr [i])){
if(symbolarr [i-1] !=+& symbolarr [i + 1]!=+){
返回false;
}
}
}
返回true;
}

问题是当我测试案例时 SimpleSymbols (+ a =)我得到 true 我已经阅读了几次代码,无法调试。任何人都可以发现错误吗?

解决方案

调整解决方案



替换& && ,它们意味着非常不同的东西。



次要评论:您不需要将字符串拆分为数组来访问其字符;您可以使用 str [i] 直接访问它们。



忽略表示您需要进行范围检查的评论者: arr [-1] 将返回 undefined ,这将不等于 + 正如您所料。



正则表达式解决方案



测试是否存在正则表达式给出无效序列。如果它在那里,字符串是非法的。

  function SimpleSymbols(str){
return!/([^ + ] | ^)[A-ZA-Z]([^ +] | $)/)测试(STR)。
}

英文:



< pre class =lang-none prettyprint-override> 测试是否存在以下正则表达式:
查找除+之外的任何字符,或字符串
的开头,后跟一个字母
后跟+以外的任何字符,或者字符串结尾
如果存在,则返回false,否则为true



状态机方法



考虑编写此类程序的有用方法是作为状态机。我们将使用三种状态:开始开头, has_plus 当我们看到加号时, c $ c> need_plus 当我们需要一封加号后加号。

  function SimpleSymbols(str ){
var state =start;
var alpha = / [A-Za-z] /;

for(var i = 0; i< str.length; i ++){
var type = alpha.test(str [i])? 'letter':str [i] ==='+'? '加':'其他';

switch(state){
casestart:
switch(type){
case'letter':return false;
case'plus'state =have_plus;打破;
case'other':break;
}
休息;
caseneed_plus:
switch(type){
case'letter':return false;
case'plus':state =have_plus;打破;
case'other':return false;
}
休息;
casehave_plus:
switch(type){
case'letter':state =need_plus;打破;
case'plus':break;
case'other':state =start;打破;
}
休息;
}

}
如果(state ===need_plus)返回false;
返回true;
}

它有点长,但可能更具可读性和可维护性。但我们可以做得更好。我们将状态逻辑封装在数据结构中,如下所示:

  var transitions = {
start:{letter: 失败,加上:have_plus,其他:开始},
need_plus:{letter:fail,加上:have_plus,其他:失败},
have_plus:{信:need_plus,加上:have_plus,其他:开始},
失败:{letter:fail,加上:失败,其他:失败}
};

现在我们的程序只运行状态机:

  function SimpleSymbols(str){
var state =start,
alpha = / [A-Za-z] /;

for(var i = 0; i< str.length; i ++){
var type = alpha.test(str [i])? 'letter':str [i] ==='+'? '加':'其他';
state = transitions [state] [type];
}
返回状态!=失败;
}

我们可以将其捆绑到状态机对象中:

  function stateMachine(state,transitions){
return {
go:function(type){state = transitions [state ][类型]; }
state:function(){return state; }
};
}

现在我们可以将`SimpleSymbols'写成

  function SimpleSymbols(str){
var machine = stateMachine(start,transitions),
alpha = / [A-Za Z] /;

for(var i = 0; i< str.length; i ++){
var type = alpha.test(str [i])? 'letter':str [i] ==='+'? '加':'其他';
machine.go(type);
}
返回machine.state()!=失败;
}

将标记的分类与运行逻辑分开是一种好习惯机器:

  function token_type(c){
return /A-Za-z]/.test(str [一世]) ? 'letter':str [i] ==='+'? '加':'其他';
}

然后只需

  function SimpleSymbols(str){
var machine = stateMachine(start,transitions);
for(var i = 0; i< str.length; i ++){machine.go(token_type(str [i])); }
返回machine.state()!=失败;
}


I am doing a problem on coderbyte and the problem is as follows:

Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.

The code that I have written is this:

var SimpleSymbols = function(str){
    var alpha = /[A-Za-z]/;
    var symbolarr = str.split("");
    for(var i = 0; i < symbolarr.length; i++) {
        if(alpha.test(symbolarr[i])) { 
            if(symbolarr[i-1] != "+" & symbolarr[i+1] != "+") {
                return false;
            }
        }
    }   
    return true;
}    

The problem is that when I test the case SimpleSymbols("+a=") I am getting true I have read through my code a few times and can't debug this. Can anyone spot the error?

解决方案

Tweaking your solution

Replace & with &&, they mean very different things.

Minor comment: you don't need to split the string into an array to access its characters; you can access them directly with str[i].

Ignore the commenter who said you need a range check: arr[-1] will just return undefined, which will not be equal to + as you would expect.

Regexp solution

Test for the presence of a regexp giving the invalid sequence. If it's there, the string is illegal.

function SimpleSymbols(str) {
    return !/([^+]|^)[A-Za-z]([^+]|$)/).test(str);
}

In English:

Test for the presence of the following regexp:
    Find any character other than +, or the beginning of the string
    followed by a letter
    followed by any character other than +, or the end of the string
If it is present, return false, else true

State machine approach

A useful way to think about writing such programs is as a state machine. We will use three states: start for the beginning, have_plus when we have just seen a plus sign, and need_plus when we need a plus sign following a letter.

function SimpleSymbols(str) {
    var state = "start";
    var alpha = /[A-Za-z]/;

    for (var i = 0; i < str.length; i++) {
        var type = alpha.test(str[i]) ? 'letter' : str[i] === '+' ? 'plus' : 'other';

        switch (state) {
            case "start":
                switch (type) {
                    case 'letter':                      return false;
                    case 'plus'    state = "have_plus"; break;
                    case 'other':                       break; 
                }
                break;
            case "need_plus":
                switch (type) {
                    case 'letter':                      return false;
                    case 'plus':   state = "have_plus"; break;
                    case 'other':                       return false;
                }
                break;
            case "have_plus":
                switch (type) {
                    case 'letter': state = "need_plus"; break;
                    case 'plus':                        break;
                    case 'other':  state = "start";     break;
                }
                break;
        }

    }
    if (state === "need_plus") return false;
    return true;
}

It's a little longer, but it might be more readable and more maintainable. But we can do better. We will encapsulate the state logic in a data structure as follows:

var transitions = {
    start:     {letter: "fail",      plus: "have_plus",   other: "start"},
    need_plus: {letter: "fail",      plus: "have_plus",   other: "fail"},
    have_plus: {letter: "need_plus", plus: "have_plus",   other: "start"},
    fail:      {letter: "fail",      plus: "fail",        other: "fail"}
};

Now our program just runs through the state machine:

function SimpleSymbols(str) {
    var state = "start",
        alpha = /[A-Za-z]/;

    for (var i = 0; i < str.length; i++) {
        var type = alpha.test(str[i]) ? 'letter' : str[i] === '+' ? 'plus' : 'other';
        state = transitions[state][type];
    }
    return state != "fail";
}

We could bundle this up into a state-machine object:

function stateMachine(state, transitions) {
    return {
        go: function(type) { state = transitions[state][type]; }
        state: function() { return state; }
    };
}

Now we can write `SimpleSymbols' as

function SimpleSymbols(str) {
    var machine = stateMachine("start", transitions),
        alpha = /[A-Za-z]/;

    for (var i = 0; i < str.length; i++) {
        var type = alpha.test(str[i]) ? 'letter' : str[i] === '+' ? 'plus' : 'other';
        machine.go(type);
    }
    return machine.state() != "fail";
}

It would be good practice to disentangle the classification of tokens from the logic for running the machine:

function token_type(c) {
    return /A-Za-z]/.test(str[i]) ? 'letter' : str[i] === '+' ? 'plus' : 'other';
}

Then just

function SimpleSymbols(str) {
    var machine = stateMachine("start", transitions);
    for (var i = 0; i < str.length; i++) { machine.go(token_type(str[i])); }
    return machine.state() != "fail";
}

这篇关于在Javascript中检查字符串中的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆