字符串反转

字符串反转可以通过多种编程语言和方法实现。以下是一些常见编程语言中实现字符串反转的方法:

C语言

#include <stdio.h>
#include <string.h>

void reverseString(char* str) {
    int length = strlen(str);
    for (int i = 0; i < length / 2; i++) {
        char temp = str[i];
        str[i] = str[length - 1 - i];
        str[length - 1 - i] = temp;
    }
}

int main() {
    char str[] = "Hello, World!"printf("Original string: %s\n", str);
    reverseString(str);
    printf("Reversed string: %s\n", str);
    return 0;
}

C++

#include <iostream>
#include <algorithm>
#include <string>

std::string reverseString(std::string str) {
    std::reverse(str.begin(), str.end());
    return str;
}

int main() {
    std::string str = "Hello, World!";
    std::cout << "Original string: " << str << std::endl;
    std::cout << "Reversed string: " << reverseString(str) << std::endl;
    return 0;
}

Go语言

package main

import (
    "fmt"
)

func reverseString(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func main() {
    str := "Hello, World!"
    fmt.Println("Original string:", str)
    fmt.Println("Reversed string:", reverseString(str))
}

Java

public class StringReversalExample {
    public static void main(String[] args) {
        String original = "Hello, World!"StringBuilder sb = new StringBuilder(original);
        String reversed = sb.reverse().toString();
        System.out.println(reversed); // 输出: !dlroW ,olleH
    }
}

Python

def reverse_string(s):
    return s[::-1]

original = "Hello, World!"
reversed = reverse_string(original)
print(reversed)  # 输出: !dlroW ,olleH

Excel

在Excel中,可以使用以下方法反转字符串:

  1. 使用“快速填充”功能来反转列中的字符串。

  2. 自定义函数,例如使用LETSEQUENCE函数结合MID函数来反转字符串。

JavaScript

function reverseString(s) {
    let arr = s.split('');
    for (let i = 0; i < arr.length / 2; i++) {
        let temp = arr[i];
        arr[i] = arr[arr.length - 1 - i];
        arr[arr.length - 1 - i] = temp;
    }
    return arr.join('');
}

let str = 'abcdef'let newStr = reverseString(str);
console.log('反转前的字符串:', str); // abcdef
console.log('反转后的字符串:', newStr); // fedcba

C#

using System;

class Program {
    static void Main() {
        string content = "Say Hello World"string reverseString = new string(content.Reverse().ToArray());
        Console.WriteLine(reverseString); // 输出: !dlroW ,olleH
    }
}

总结

以上方法涵盖了多种编程语言和不同的实现方式,包括手动遍历、双指针、递归、切片等。根据具体需求和编程环境选择合适的方法可以实现字符串反转。

Top