You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除未知长度字符串的首尾字符并计算剩余字符长度

解决方法:获取字符串尾字符并计算排除首尾后的长度

不管用什么编程语言,核心思路都是先拿到字符串的长度,再通过长度减1定位最后一个字符的索引;或者直接用语言自带的负索引/便捷方法获取尾字符。下面是几种常用语言的实现示例:

Python

Python支持负索引,直接用[-1]就能取到最后一个字符,无需提前计算长度:

word = input("请输入单词:")
# 处理边界情况:字符串长度小于2时无法排除首尾
if len(word) < 2:
    print("输入的字符串长度太短,无法排除首尾字符")
else:
    # 获取尾字符(如果不需要可以跳过这行)
    last_char = word[-1]
    # 计算排除首尾后的长度
    result_len = len(word) - 2
    print(f"{result_len}(by excluding first and last char of string.)")

Java

Java中通过str.length()获取长度,最后一个字符的索引是长度-1:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入单词:");
        String word = scanner.nextLine();
        
        if (word.length() < 2) {
            System.out.println("输入的字符串长度太短,无法排除首尾字符");
            return;
        }
        // 获取尾字符
        char lastChar = word.charAt(word.length() - 1);
        int resultLen = word.length() - 2;
        System.out.println(resultLen + "(by excluding first and last char of string.)");
    }
}

JavaScript

JavaScript里可以像数组一样通过索引访问字符串,最后一个索引为str.length - 1:

const word = prompt("请输入单词:");
if (word.length < 2) {
    alert("输入的字符串长度太短,无法排除首尾字符");
} else {
    // 获取尾字符
    const lastChar = word[word.length - 1];
    const resultLen = word.length - 2;
    console.log(`${resultLen}(by excluding first and last char of string.)`);
}

补充说明

所有语言的核心逻辑都是:排除首尾后的长度 = 字符串总长度 - 2。如果输入的字符串长度小于2(比如空串、单字符),需要额外处理避免出现负数结果。

内容的提问来源于stack exchange,提问作者Akshay Agantham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:15:34