博客
关于我
7.5写一个函数,使输入的一个字符串按反序存放,在主函数中输入和输出字符串。
阅读量:371 次
发布时间:2019-03-05

本文共 970 字,大约阅读时间需要 3 分钟。

写一个函数,实现字符串反转

问题描述

编写一个函数,将输入的字符串按反序存放。主函数将从标准输入读取字符串并输出结果。

函数实现

#include 
#include
void reverse(char s[]) { int i, j, len = strlen(s); char t; for(i = 0, j = len - 1; i < j; i++) { t = s[i]; s[i] = s[j]; s[j] = t; j--; }}

使用说明

  • 函数定义void reverse(char s[]) 定义了一个函数 reverse,接受一个字符数组 s

  • 函数逻辑

    • 计算字符串长度 len
    • 使用双指针 ij,分别从字符串的开头和末尾移动。
    • i 小于 j 时,交换 s[i]s[j] 的值,并将 j 递减,i 递增。
    • 通过这种方式,从两端向中间逐步交换字符,实现字符串反转。
  • 主函数

    • 读取用户输入的字符串。
    • 调用 reverse 函数进行反转处理。
    • 输出处理后的字符串。
  • 示例代码

    #include 
    #include
    void reverse(char s[]) { int i, j, len = strlen(s); char t; for(i = 0, j = len - 1; i < j; i++) { t = s[i]; s[i] = s[j]; s[j] = t; j--; }}int main() { char input[100]; printf("请输入一个字符串:"); scanf("%s", input); reverse(input); printf("反转后的字符串:\n%s", input); return 0;}

    总结

    通过上述代码,我们成功实现了字符串反转功能。函数 reverse 使用双指针法高效地完成了字符串反转操作。整个过程逻辑清晰,易于理解和修改。

    转载地址:http://szag.baihongyu.com/

    你可能感兴趣的文章
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>
    Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
    查看>>
    Node-RED中实现HTML表单提交和获取提交的内容
    查看>>