[英]Copy a string to another string
I am following this algorithm that will copy one string to another string:我正在遵循将一个字符串复制到另一个字符串的算法:
[S is a source string and T is a target string]
1. Set I = 0
2. Repeat step 3 while S[I] ≠ Null do
3. T[I] = S[I]
4. I = I + 1
[End of loop]
5. Set T[I] = Null
6. Return
I have attempted it but it instead removes the first n
characters from source string relative to length of target string.我已经尝试过,但它会从源字符串中删除相对于目标字符串长度的前
n
字符。 For example:例如:
#include <stdio.h>
#include <stdlib.h>
char const* stringCopy(char* T, char const* S){
while(*S){
*T++ = *S++;
}
//*T = 0;
return T;
}
int main(void){
char sentence[100] = "some sentence";
char* again = "another";
printf("%s", stringCopy(sentence, again));
return EXIT_SUCCESS;
}
You return the incremented original pointer T. Make a copy of T for the copy loop and return the original pointer.您返回增加后的原始指针 T。为复制循环制作 T 的副本并返回原始指针。
#include <stdio.h>
#include <stdlib.h>
char const* stringCopy(char* T, char const* S){
char *ptr = T;
while(*ptr++ = *S++);
return T;
}
int main(void){
char sentence[100] = "some sentence";
char* again = "another";
printf("%s", stringCopy(sentence, again));
return EXIT_SUCCESS;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.