即使最后一个字符是分隔符,也要分割字符串 [英] Split a string even if the last character is a delimiter

查看:76
本文介绍了即使最后一个字符是分隔符,也要分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除字符串末尾的一些字符.

I want to delete some characters at the end of a string.

我做了这个功能:

(defun del-delimiter-at-end (string)
  (cond
    ((eq (delimiterp (char string (- (length string) 1))) nil) 
        string )
    (t 
        (del-delimiterp-at-end (subseq string 0 (- (length string) 1))) ) ) )

与此:

(defun delimiterp (c) (position c " ,.;!?/"))

但是我不明白为什么它不起作用.我有以下错误:

But I don't understand why it doesn't work. I have the following error :

Index must be positive and not -1

请注意,我想在字符串列表中分割一个字符串,我已经在这里查看了:

Note that I want to split a string in list of strings, I already looked here :

Lisp-将输入拆分为单独的字符串

但是如果字符串的末尾是定界符,它将不起作用,这就是为什么我要这样做的原因.

but it doesn't work if the end of the string is a delimiter, that's why I'm trying to do that.

我做错了什么? 预先感谢.

What am I doing wrong? Thanks in advance.

推荐答案

简单方法

只需使用 string-right-trim :

(string-right-trim " ,.;!?/" s)

您的错误

如果将空字符串传递给del-delimiter-at-end,则将把-1作为第二个参数传递给

Your Error

If you pass an empty string to you del-delimiter-at-end, you will be passing -1 as the second argument to char.

  1. 没有理由做(eq (delimiterp ...) nil);只需使用(delimiterp ...)代替(并切换条款!)

  1. There is no reason to do (eq (delimiterp ...) nil); just use (delimiterp ...) instead (and switch the clauses!)

使用 if 而不是 cond ,只有两个子句,每个子句只有一种形式.

It is mode idiomatic to use if and not cond when you have just two clauses and each has just one form.

您递归地调用 subseq ,这意味着您不仅分配了毫无理由的记忆,您的算法的字符串长度也是二次.

这篇关于即使最后一个字符是分隔符,也要分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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