Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

undefined: while #22

Open
Chanyon opened this issue Oct 15, 2022 · 3 comments
Open

undefined: while #22

Chanyon opened this issue Oct 15, 2022 · 3 comments
Labels
enhancement New feature or request

Comments

@Chanyon
Copy link

Chanyon commented Oct 15, 2022

string S = "abcdefx";
string T = "def";
int myIndex(string S,string T,int pos) {
  int i = pos;
  int j = 0;
  byte[] s = toByteArray(S);
  byte[] t = toByteArray(T);

  int slen = len(s);
  int tlen = len(t);
  while(i <= slen && j <= tlen) { //undefined: while
  // for(i <= slen && j <= tlen) {
    if (s[i] == s[j]) {
      i += 1;
      j += 1;
    }else{
      i = i - j + 1;
      j = 0;
    }
  }
  if (j == tlen) {
    return i - tlen;
  } else {
    return 0;
  }
}

int res = myIndex(S,T,0);
println(res);
@crossoverJie
Copy link
Owner

感谢反馈,GScript 目前并没有提供 while 关键字,可直接使用 for 循环替代。

image

我调整了一下,你是想实现这个算法吧?计算出 T 第一次出现在 S 中的位置。

目前暂不支持 += 语法和数组直接比较 s[i] == s[j] ,后续会逐步完善。

调整后可运行的代码:

string S = "abcdefx";
string T = "def";
int myIndex(string S,string T,int pos) {
  int i = pos;
  int j = 0;
  byte[] s = toByteArray(S);
  byte[] t = toByteArray(T);

  int slen = len(s);
  int tlen = len(t);
  for(i <= slen && j <= tlen) {
	byte si = s[i];
	byte sj = s[j];
    if (si == sj) {
      i = i+1;
      j = j+1;
    }else{
      i = i - j + 1;
      j = 0;
    }
  }
  if (j == tlen) {
    return i - tlen;
  } else {
    return slen-i;
  }
}

int res = myIndex(S,T,0);
println(res);

@crossoverJie crossoverJie added the enhancement New feature or request label Oct 15, 2022
@Chanyon
Copy link
Author

Chanyon commented Oct 16, 2022

//enhancement
string str = "foo";
char[] ch = str.chars(); //转换为字符数组,可以通过index拿到单个字符
//or
string s = str.get(index);

@Chanyon
Copy link
Author

Chanyon commented Oct 16, 2022

class Strings {
    string get(string str,int index) {
        byte[] bs = toByteArray(str);
        int idx = index;
        if(idx >= len(bs)) {
            return nil;
        }else {
            return toString(bs[idx: idx + 1]);
        }
    }
}
Strings s = Strings();
string foo = "foo";
string f = s.get(foo,0);
println(f); //expected f = "f";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants