示例#1
0
// LastIndexFunc returns the index into s of the last Unicode code point
// satisfying f(c) or -1 if none do
func LastIndexFunc(s string, f func(rune) bool) int {
	function := func(c rune) bool {
		return unicode.Is(unicode.Han, c)
	}

	fmt.Println(strings.LastIndexFunc("hello 世界", function))    // 10 一个汉字貌似占3个位置
	fmt.Println(strings.LastIndexFunc("hello world", function)) // -1
	return strings.LastIndexFunc(s, f)
}
示例#2
0
// Caller report caller's position with file:function:line format
// depth means which caller, 0 means yourself, 1 means your caller
func Caller(depth int) string {
	_, file, line, _ := runtime.Caller(depth + 1)
	i := strings.LastIndexFunc(file, pathSepFunc)
	if i >= 0 {
		j := strings.LastIndexFunc(file[:i], pathSepFunc)
		if j >= 0 {
			i = j
		}
		file = file[i+1:]
	}
	return fmt.Sprintf("%s:%d", file, line)
}
示例#3
0
func main() {
	as := ""
	for _, char := range []rune{'A', 0xE6, 0346, 330, '\xE6', '\u00E6'} {
		fmt.Printf("[0x%x '%c']", char, char)
		as += string(char)
	}
	fmt.Println(as)
	line := "Θ£ 123 Θ £ £Θ" //Θ and £  not only one char
	i := strings.Index(line, " ")
	i2 := strings.IndexFunc(line, unicode.IsSpace)
	firstword := line[:i]
	j := strings.LastIndex(line, " ")
	j2 := strings.LastIndexFunc(line, unicode.IsSpace)
	lastword := line[j+1:]
	item, size := utf8.DecodeRuneInString(line[j+1:]) //返回第一个字符(可能超过一般的ascii码)和字节数
	fmt.Println(i, ",", i2, ",", firstword, ",", j, ",", j2, lastword, item, size)
	bs:="{\"error\":\"thumbnail's arg is out of range: 650001456812x\"}"
	i=strings.Index(bs,":")
	j=strings.LastIndex(bs,"}")
	fmt.Println(bs[i+2:j-1])
	

	var iss []int{1,2,3}
	fmt.Println()
}
示例#4
0
文件: config.go 项目: reiver/turtledq
func NewTurtleConfig(syslogLog *syslog.Writer) (*TurtleConfig, error) {

	//DEBUG
	syslogLog.Notice("    [CONFIG] BEGIN.")

	cmdPath := os.Args[0]
	cmdPathLastSlash := strings.LastIndexFunc(cmdPath, func(c rune) bool {
		return '/' == c
	})

	cmdDirPath := cmdPath[0:cmdPathLastSlash]

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] command path: [%v]", cmdPath))
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] command path last slash: [%v]", cmdPathLastSlash))
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] command dir path: [%v]", cmdDirPath))

	confRelativePath := "turtledq.ini"
	confPath := cmdDirPath + "/" + confRelativePath

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] settings file relative path: [%v]", confRelativePath))
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] settings file absolute path: [%v]", confPath))

	return NewTurtleConfigFromFile(syslogLog, confPath)
}
示例#5
0
// ParseTime parses the time interval from s, and returns it
// as nanoseconds, if it is representable in seconds (with
// isNanoSeconds true), or sample count (with isNanoSeconds false)
// if not.
func ParseTime(s string) (t Time, err os.Error) {
	endi := strings.LastIndexFunc(s, isDigit) + 1
	if endi == 0 {
		return Time{}, os.NewError("invalid number")
	}
	number, suffix := s[0:endi], s[endi:]
	var mult int64
	switch suffix {
	case "s", "":
		mult = 1e9
	case "ms":
		mult = 1e6
	case "us":
		mult = 1e3
	case "ns":
		mult = 1
	case "x": // samples
		mult = 1
	}
	// use exact arithmetic if we can
	d, err := strconv.Atoi64(number)
	if err != nil {
		f, err := strconv.Atof64(number)
		if err != nil {
			return Time{}, err
		}
		d = int64(f * float64(mult))
	} else {
		d *= mult
	}
	return Time{d, suffix != "x"}, nil
}
示例#6
0
文件: phrase.go 项目: pto/go-book
func main() {
	phrase := "naïve\u2028🚀"
	fmt.Printf("string: %s\n", phrase)
	fmt.Println("len:", len(phrase),
		"RuneCountInString:", utf8.RuneCountInString(phrase))
	fmt.Println("index rune     char bytes")
	for index, char := range phrase {
		fmt.Printf(" %2d   %-8U  %c    % X\n",
			index, char, char, []byte(string(char)))
	}
	last_rune, length := utf8.DecodeLastRuneInString(phrase)
	fmt.Printf("last rune: 0x%x length: %d\n", last_rune, length)
	fmt.Printf("length of string: %d length of []rune: %d\n",
		len(phrase), len([]rune(phrase)))
	fmt.Printf("line separator: %[1]U 0x%[1]x '%[1]c' %s\n", '\u2028', string('\u2028'))
	fmt.Printf("paragraph separator: %[1]U 0x%[1]x '%[1]c' %s\n", '\u2029', string('\u2029'))

	line := "rå tørt\u2028vær"
	i := strings.IndexFunc(line, unicode.IsSpace)
	firstWord := line[:i]
	j := strings.LastIndexFunc(line, unicode.IsSpace)
	_, size := utf8.DecodeRuneInString(line[j:])
	lastWord := line[j+size:]
	fmt.Println("size of space:", size)
	fmt.Println(firstWord, lastWord)
}
示例#7
0
// Word returns a string with the word of the view's internal buffer
// at the position corresponding to the point (x, y).
func (v *View) Word(x, y int) (string, error) {
	x, y, err := v.realPosition(x, y)
	if err != nil {
		return "", err
	}

	if x < 0 || y < 0 || y >= len(v.lines) || x >= len(v.lines[y]) {
		return "", errors.New("invalid point")
	}

	str := lineType(v.lines[y]).String()

	nl := strings.LastIndexFunc(str[:x], indexFunc)
	if nl == -1 {
		nl = 0
	} else {
		nl = nl + 1
	}
	nr := strings.IndexFunc(str[x:], indexFunc)
	if nr == -1 {
		nr = len(str)
	} else {
		nr = nr + x
	}
	return string(str[nl:nr]), nil
}
示例#8
0
func main() {
	fmt.Println(strings.Index("Hello, world!", "He"))  // 0: He가 맨 처음에 있으므로 0
	fmt.Println(strings.Index("Hello, world!", "wor")) // 7: wor가 8번째에 있으므로 7
	fmt.Println(strings.Index("Hello, world!", "ow"))  // -1: ow는 없으므로 -1

	fmt.Println(strings.IndexAny("Hello, world!", "eo")) // 1: e가 2번째에 있으므로 1
	fmt.Println(strings.IndexAny("Hello, world!", "f"))  // -1: f는 없으므로 -1

	var c byte
	c = 'd'
	fmt.Println(strings.IndexByte("Hello, world!", c)) // 11: d가 12번째에 있으므로 11
	c = 'f'
	fmt.Println(strings.IndexByte("Hello, world!", c)) // -1: f는 없으므로 -1

	var r rune
	r = '언'
	fmt.Println(strings.IndexRune("고 언어", r)) // 4: "언"이 시작되는 인덱스가 4

	f := func(r rune) bool {
		return unicode.Is(unicode.Hangul, r) // r이 한글 유니코드이면 true를 리턴
	}
	fmt.Println(strings.IndexFunc("Go 언어", f))       // 3: 한글이 4번째부터 시작하므로 3
	fmt.Println(strings.IndexFunc("Go Language", f)) // -1: 한글이 없으므로 -1

	fmt.Println(strings.LastIndex("Hello Hello Hello, world!", "Hello"))
	// 12: 마지막 Hello가 13번째에 있으므로 12

	fmt.Println(strings.LastIndexAny("Hello, world", "ol")) // 10: 마지막 l이 11번째에 있으므로 10

	fmt.Println(strings.LastIndexFunc("Go 언어 안녕", f)) // 13: 마지막 한글인 '녕'이 시작되는 인덱스가 13
}
示例#9
0
func moveDotLeftWord(ed *Editor) {
	if ed.dot == 0 {
		return
	}
	space := strings.LastIndexFunc(
		strings.TrimRightFunc(ed.line[:ed.dot], unicode.IsSpace),
		unicode.IsSpace) + 1
	ed.dot = space
}
示例#10
0
// NOTE(xiaq): A word is now defined as a series of non-whitespace chars.
func killWordLeft(ed *Editor) {
	if ed.dot == 0 {
	}
	space := strings.LastIndexFunc(
		strings.TrimRightFunc(ed.line[:ed.dot], unicode.IsSpace),
		unicode.IsSpace) + 1
	ed.line = ed.line[:space] + ed.line[ed.dot:]
	ed.dot = space
}
示例#11
0
func lastWord(s string) string {

	idx := strings.LastIndexFunc(s, func(c rune) bool {
		return c >= 'A' && c <= 'Z'
	})
	if idx >= 0 {
		return s[idx:]
	}
	return ""
}
示例#12
0
文件: builtins.go 项目: horryq/elvish
// NOTE(xiaq): A word is now defined as a series of non-whitespace chars.
func killWordLeft(ed *Editor, k Key) *leReturn {
	if ed.dot == 0 {
		return nil
	}
	space := strings.LastIndexFunc(
		strings.TrimRightFunc(ed.line[:ed.dot], unicode.IsSpace),
		unicode.IsSpace) + 1
	ed.line = ed.line[:space] + ed.line[ed.dot:]
	ed.dot = space
	return nil
}
示例#13
0
func TestIndexFunc(t *testing.T) {
	for _, tc := range indexFuncTests {
		first := strings.IndexFunc(tc.s, tc.f)
		if first != tc.first {
			t.Errorf("strings.IndexFunc(%q, %s) = %d; want %d", tc.s, tc.fname, first, tc.first)
		}
		last := strings.LastIndexFunc(tc.s, tc.f)
		if last != tc.last {
			t.Errorf("strings.LastIndexFunc(%q, %s) = %d; want %d", tc.s, tc.fname, last, tc.last)
		}
	}
}
示例#14
0
文件: strings.go 项目: bmatsuo/goline
//  Returns the index i of the longest terminal substring s[i:] such that f
//  returns true for all runes in s[i:]. Returns -1 if there is no such i.
func stringSuffixIndexFunc(s string, f func(c rune) bool) (i int) {
	var hasSuffix bool
	i = strings.LastIndexFunc(s, func(c rune) (done bool) {
		if done = !f(c); !hasSuffix {
			hasSuffix = !done
		}
		return
	})
	if i++; !hasSuffix {
		i = -1
	}
	return
}
示例#15
0
// splitAtNumber splits given string into prefix and numeric suffix.
// If no numeric suffix exists, full original string is returned as
// prefix with -1 as a suffix.
func splitAtNumber(str string) (string, int) {
	i := strings.LastIndexFunc(str, func(r rune) bool {
		return !unicode.IsDigit(r)
	}) + 1
	if i == len(str) {
		// no numeric suffix
		return str, -1
	}
	n, err := strconv.Atoi(str[i:])
	if err != nil {
		panic(fmt.Sprintf("parsing number %v: %v", str[i:], err)) // should never happen
	}
	return str[:i], n
}
示例#16
0
func main() {
	as := ""
	for _, char := range []rune{'A', 0xE6, 0346, 330, '\xE6', '\u00E6'} {
		fmt.Printf("[0x%x '%c']", char, char)
		as += string(char)
	}
	fmt.Println(as)
	line := "Θ£ 123 Θ £ £Θ" //Θ and £  not only one char
	i := strings.Index(line, " ")
	i2 := strings.IndexFunc(line, unicode.IsSpace)
	firstword := line[:i]
	j := strings.LastIndex(line, " ")
	j2 := strings.LastIndexFunc(line, unicode.IsSpace)
	lastword := line[j+1:]
	item, size := utf8.DecodeRuneInString(line[j+1:]) //返回第一个字符(可能超过一般的ascii码)和字节数
	fmt.Println(i, ",", i2, ",", firstword, ",", j, ",", j2, lastword, item, size)
}
示例#17
0
func (r *FormatedReporter) breakLine(str, lead string) string {
	if len(str) <= r.width {
		return str
	}

	result := ""
	for len(str) > r.width {
		idx := strings.LastIndexFunc(str[0:r.width], func(ch rune) bool {
			return unicode.IsSpace(ch)
		})
		if idx <= 0 {
			idx = r.width
		}
		result += str[0:idx] + "\n" + lead
		str = str[idx:]
	}
	result += str
	return result
}
示例#18
0
func (q *Query) shouldPrepare() bool {

	stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
		return unicode.IsSpace(r) || r == ';'
	}), unicode.IsSpace)

	var stmtType string
	if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
		stmtType = strings.ToLower(stmt[:n])
	}
	if stmtType == "begin" {
		if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
			stmtType = strings.ToLower(stmt[n+1:])
		}
	}
	switch stmtType {
	case "select", "insert", "update", "delete", "batch":
		return true
	}
	return false
}
示例#19
0
文件: conn.go 项目: kballard/goirc
func (c *Conn) badNick(oldnick string, errCode int) string {
	if oldnick == "" {
		// where's our nick?
		c.Shutdown()
		return ""
	}
	if oldnick != lastNick && strings.HasPrefix(lastNick, oldnick) {
		// must have been too long
		idx := strings.LastIndexFunc(oldnick, func(r rune) bool { return r != '_' })
		if idx == -1 {
			// our entire nick is _'s?
			c.Shutdown()
			return ""
		}
		_, size := utf8.DecodeRuneInString(oldnick[idx:])
		oldnick = oldnick[:idx] + "_" + oldnick[idx+size:]
	} else {
		oldnick += "_"
	}
	lastNick = oldnick
	return oldnick
}
示例#20
0
文件: view.go 项目: apcera/gocui
// Word returns a string with the word of the view's internal buffer
// at the position corresponding to the point (x, y).
func (v *View) Word(x, y int) (string, error) {
	x = v.ox + x
	y = v.oy + y

	if y < 0 || y >= len(v.lines) || x >= len(v.lines[y]) {
		return "", errors.New("invalid point")
	}
	l := string(v.lines[y])
	nl := strings.LastIndexFunc(l[:x], indexFunc)
	if nl == -1 {
		nl = 0
	} else {
		nl = nl + 1
	}
	nr := strings.IndexFunc(l[x:], indexFunc)
	if nr == -1 {
		nr = len(l)
	} else {
		nr = nr + x
	}
	return string(l[nl:nr]), nil
}
示例#21
0
func newFragment(text *utf8string.String, left, right, length int) (*Fragment, *Theme) {
	match := text.Slice(left, left+length)
	if trimLeft := strings.IndexFunc(match, notWhitespace); trimLeft != -1 {
		unicodeTrim := utf8.RuneCountInString(match[:trimLeft])
		match = match[trimLeft:]
		left += unicodeTrim
		right += unicodeTrim
		length -= unicodeTrim
	}
	if trimmedLength := strings.LastIndexFunc(match, notWhitespace) + 1; trimmedLength != 0 {
		unicodeTrim := utf8.RuneCountInString(match[trimmedLength:])
		match = match[:trimmedLength]
		length -= unicodeTrim
	}
	theme := newTheme(match)
	return &Fragment{
		Left:   left,
		Right:  right,
		Length: length,
		Id:     theme.Id,
	}, theme
}
示例#22
0
文件: view.go 项目: hako/dry
// Word returns a string with the word of the view's internal buffer
// at the position corresponding to the point (x, y).
func (v *View) Word(x, y int) (string, error) {
	x, y, err := v.realPosition(x, y)
	if err != nil {
		return "", err
	}

	if x < 0 || y < 0 || y >= len(v.lines) || x >= len(v.lines[y]) {
		return "", invalidPointError(x, y)
	}
	l := string(v.lines[y])
	nl := strings.LastIndexFunc(l[:x], indexFunc)
	if nl == -1 {
		nl = 0
	} else {
		nl = nl + 1
	}
	nr := strings.IndexFunc(l[x:], indexFunc)
	if nr == -1 {
		nr = len(l)
	} else {
		nr = nr + x
	}
	return string(l[nl:nr]), nil
}
示例#23
0
func main() {
	fmt.Println(strings.LastIndexFunc("nihaoma", split)) //6
}
示例#24
0
文件: lexer.go 项目: mabu/yail
func (l *lexer) run() {
	defer close(l.lexemes)
Start:
	for r, s := l.next(); r != eof; r, s = l.next() {
		if lex, ok := runeLexeme[r]; ok {
			l.emit(lex, s)
			continue
		}
		if unicode.IsSpace(r) {
			l.pos += s
			continue
		}
		if r == '/' {
			l.pos += s
			switch r2, s2 := l.next(); r2 {
			case '/': // single line comment
				l.pos += s2
				l.skipUntil("\n")
				l.emit(lexEos, 0)
				continue Start
			case '*': // comment
				l.pos += s2
				l.skipUntil("*/")
				continue Start
			default:
				l.pos -= s
			}
		}
		for str, lex := range twoRunesLexeme {
			if strings.HasPrefix(l.input[l.pos:], str) {
				l.emit(lex, len(str))
				continue Start
			}
		}
		for str, lex := range stringLexeme {
			if strings.HasPrefix(l.input[l.pos:], str) {
				r, _ := utf8.DecodeRuneInString(l.input[l.pos+len(str):])
				if !isAlphaNum(r) {
					l.emit(lex, len(str))
					continue Start
				}
			}
		}
		if lex, ok := conflictingRuneLexeme[r]; ok {
			l.emit(lex, s)
			continue
		}
		if unicode.IsNumber(r) {
			i := strings.IndexFunc(l.input[l.pos+s:], notNumber)
			if i == -1 {
				l.emit(lexInt, len(l.input)-l.pos)
			} else if l.input[l.pos+s+i] == '.' {
				i++
				j := strings.IndexFunc(l.input[l.pos+s+i:], notNumber)
				if j == -1 {
					l.emit(lexFloat, len(l.input)-l.pos)
				} else {
					l.emit(lexFloat, s+i+j)
				}
			} else {
				l.emit(lexInt, s+i)
			}
		} else if r == '"' { // string
			i := strings.Index(l.input[l.pos+s:], "\"")
			for i != -1 {
				if (i-strings.LastIndexFunc(l.input[l.pos+s-1:l.pos+s+i], func(r rune) bool { return r != '\\' }))%2 == 0 {
					break
				}
				s += i + 1
				i = strings.Index(l.input[l.pos+s:], "\"")
			}
			if i == -1 {
				l.emit(lexError, len(l.input)-l.pos)
			} else {
				l.emit(lexString, s+i+1)
			}
		} else if unicode.IsLetter(r) {
			i := strings.IndexFunc(l.input[l.pos+s:], func(r rune) bool { return !isAlphaNum(r) })
			if i == -1 {
				s = len(l.input) - l.pos
			} else {
				s += i
			}
			l.emit(lexName, s)
		} else {
			l.emit(lexError, s)
			return
		}
	}
	l.emit(lexEof, 0)
}
示例#25
0
func loginGoogle(w http.ResponseWriter, r *http.Request, conf *oauth2.Config, tok *oauth2.Token) {
	client := conf.Client(oauth2.NoContext, tok)
	service, err := plus.New(client)
	if err != nil {
		response.ServerError(w, err)
		return
	}

	call := service.People.Get("me")
	person, err := call.Do()
	if err != nil {
		response.ServerError(w, err)
		return
	}

	email := ""
	for _, em := range person.Emails {
		if em.Type == "account" {
			email = em.Value
			break
		}
	}

	if !strings.HasSuffix(email, "@bartleboglehegarty.com") && email != "*****@*****.**" {
		response.ClientError(w, http.StatusForbidden)
		return
	}

	if store.HasUserWithEmail(email) {
		loginSuccess(w, r, email)
		return
	}

	firstname := person.Name.GivenName
	lastname := person.Name.FamilyName
	description := person.AboutMe
	imageURL := ""

	if !person.Image.IsDefault {
		imageURL = person.Image.Url
		if idx := strings.LastIndexFunc(
			imageURL,
			func(r rune) bool {
				return r == '?'
			},
		); idx >= 0 {
			imageURL = imageURL[:idx]
		}
	}

	fullname := firstname
	if lastname != "" {
		fullname += " " + lastname
	}

	if err := store.Register(email, "", fullname, "", description, imageURL); err != nil {
		response.ServerError(w, err)
		return
	}

	loginSuccess(w, r, email)
}
示例#26
0
func lastWord(s string) string {
	s = strings.TrimRightFunc(s, unicode.IsSpace)
	i := strings.LastIndexFunc(s, unicode.IsSpace) + 1
	return s[i:]
}
示例#27
0
func test() {

	line := "rå tørt\u2028vær"
	i := strings.IndexFunc(line, unicode.IsSpace) // i == 3
	firstWord := line[:i]
	j := strings.LastIndexFunc(line, unicode.IsSpace) // j == 9
	_, size := utf8.DecodeRuneInString(line[j:])      // size == 3
	lastWord := line[j+size:]                         // j + size == 12
	fmt.Println(firstWord, lastWord)                  // Prints: rå vær

	who := "world"
	if len(os.Args) > 1 {
		who = strings.Join(os.Args[1:], " ")
	}

	fmt.Println("Hello ", who)
	æs := ""
	for _, char := range []rune{'æ', 0xE6, 0346, 230, '\xE6', '\u00E6'} {
		fmt.Printf("[0x%X '%c'] ", char, char)
		æs += string(char)
	}
	fmt.Println(æs)

	phrase := "vått og tørt王"
	fmt.Printf("string: \"%s\"\n", phrase)
	fmt.Println("index rune char bytes", len([]rune(phrase)))
	for index, char := range phrase {
		fmt.Println(char)
		fmt.Printf("%-2d %U '%c' % X\n",
			index, char, char,
			[]byte(string(char)))
	}

	fmt.Printf("|%b|%9b|%-9b|%09b|% 9b|\n", 37, 37, 37, 37, 37)
	fmt.Printf("|%o|%#o|%# 8o|%#+ 8o|%+08o|\n", 41, 41, 41, 41, -41)
	//	i := 3931
	//	fmt.Printf("|%x|%X|%8x|%08x|%#04X|0x%04X|\n", i, i, i, i, i, i)
	fmt.Printf("%d %#04x %U '%c'\n", 0x3A6, 934, '\u03A6', '\U000003A6')

	s := "Dare to be naïve"
	fmt.Printf("|%22s|%-22s|%10s|\n", s, s, s)

	//	i := strings.Index(s, "n")
	//	fmt.Printf("|%.10s|%.*s|%-22.10s|%s|\n", s, i, s, s, s)

	slogan := "End Óréttlæti♥"
	fmt.Printf("%s\n%q\n%+q\n%#q\n", slogan, slogan, slogan, slogan)

	//for _, x := range []float64{-.258, 7194.84, -60897162.0218, 1.500089e-8} {
	//	fmt.Printf("|%20.5e|%20.5f|%s|\n", x, x, Humanize(x, 20, 5, '*', ','))
	//}

	names := " Antônio\tAndré\tFriedrich\t\t\tJean\t\tÉlisabeth\tIsabella \t"
	names = strings.Replace(names, "\t", " ", -1)
	fmt.Printf("|%s|\n", names)
	fmt.Println(strings.Join(strings.Fields(names), " "))

	asciiOnly := func(char rune) rune {
		if char > 127 {
			return '?'
		}
		return char
	}

	fmt.Println(strings.Map(asciiOnly, names))
}
示例#28
0
func main() {
	fmt.Println(strings.LastIndexFunc("astaxie", splitfunc)) //符合条件的有字符t和x,因为字符x是最后出现的位置,所以这个位置应该返回4
	fmt.Println(strings.LastIndexFunc("aaabbbb", splitfunc)) //所有的字符都不符合条件,则返回-1
}