使用strcpy快速移动字符串

本文介绍了一种通过三次使用 strcpy 函数实现字符串后 n 个字符移至前面的方法。该算法首先计算不需要移动部分的长度,然后利用临时数组进行字符复制和重组,最终完成字符串的循环移位。

//将某个字符串的后n个字符放到字符串的前面
//思路:三次运用strcpy
#include<iostream>
using namespace std;
#define MAX_LEN 20
void LoopMove ( char *pStr, int steps )
{
 int n = strlen( pStr ) - steps; //计算出不需要移动的长度
 cout<<strlen(pStr)<<endl;  //计算源字符串的长度,并且打印出来

 char tmp[MAX_LEN];
 strcpy ( tmp, pStr + n );  //将不需要移动的部分,放到tmp中去
 cout<<tmp<<endl;           //为了帮助理解
 
 strcpy ( tmp + steps, pStr);//将源字符串放到temp 第steps个开始的后面
 cout<<tmp + steps<<endl;
 *( tmp + strlen ( pStr ) ) = '\0';  //将最后一个设置为结束符
 strcpy( pStr, tmp ); // 获得最终结果
 cout<<pStr<<endl;
}
int main()
{
 char str[10]={"abcdefghi"};
 //将后面的ghi 放到最前面
 LoopMove(str, 3);
 return 0;
}

在C语言中,不使用`strcpy`函数实现字符串复制有多种方法,以下为几种常见的实现方式: #### 方法一:使用`while`循环 ```c #include <stdio.h> int main() { int i = 0; char str1[100]; char str2[100]; printf("请输入字符串-> \n"); // 注意:gets函数存在缓冲区溢出风险,建议使用fgets gets(str1); while (str1[i] != '\0') { str2[i] = str1[i]; i++; } str2[i] = '\0'; printf("str2 = "); puts(str2); return 0; } ``` 此方法通过`while`循环逐个字符复制,直到遇到字符串结束符`\0`,最后在目标字符串末尾添加结束符[^3]。 #### 方法二:使用`for`循环 ```c #include <stdio.h> void mystrcpy(char *str1, char *str2) { int i = 0; for (i = 0; str2[i]; i++) { str1[i] = str2[i]; } str1[i] = '\0'; } int main() { char a[101], b[101]; // 注意:gets函数存在缓冲区溢出风险,建议使用fgets gets(b); mystrcpy(a, b); printf("String a is:%s\n", a); printf("String b is:%s\n", b); return 0; } ``` 该方法利用`for`循环遍历源字符串,将每个字符复制到目标字符串,最后添加结束符[^5]。 #### 方法三:使用指针 ```c #include <stdio.h> void mystrcpy(char *dest, const char *src) { while (*src) { *dest = *src; dest++; src++; } *dest = '\0'; } int main() { char source[] = "Hello, World!"; char destination[20]; mystrcpy(destination, source); printf("复制后的字符串: %s\n", destination); return 0; } ``` 此方法使用指针操作,通过移动指针逐个字符复制,直到源字符串结束,最后在目标字符串末尾添加结束符。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值