[英]Get a string and extract 2 substring in c
I just want to read from input a string of the form "c4 d5" and save two substring : 我只想从输入中读取形式为“ c4 d5”的字符串并保存两个子字符串:
str1 = "c4" str1 =“ c4”
str2 = "d5" str2 =“ d5”
I tried: 我试过了:
char action[5];
char str1[2];
char str2[2];
scanf("%s", action);
strncpy(str1, &action[0], 2);
strncpy(str2, &action[3], 2);
but it gives me strange behaviors.... 但这给了我奇怪的行为。
Also as I am learning c, I'm looking for both solutions using only char * and only char[] (either in input and output). 在学习c的同时,我也在寻找仅使用char *和仅使用char [](在输入和输出中)的两种解决方案。
When you expire strange behaviour ALWAYS read the man pages of the functions you are using. 当您终止奇怪的行为时,请务必阅读所使用功能的手册页。 AC string should with almost no exceptions end with a \\0 because otherwise printf/puts will probably not only print what you want but also some random memory fragments. AC字符串几乎毫无例外应以\\ 0结尾,因为否则printf / puts可能不仅会打印您想要的内容,还会打印一些随机的内存片段。 Also the index starts at 0 so in order to get the third char you need to use [2]. 索引也从0开始,因此要获得第三个字符,您需要使用[2]。
#include <stdio.h>
int main()
{
char action[5];
char str1[3];
char str2[3];
scanf("%s", action);
strncpy(str1, action, 2);
strncpy(str2, &action[2], 2);
str1[2] = '\0';
str2[2] = '\0';
puts(str1);
puts(str2);
return 0;
}
man page of strncpy strncpy手册页
The strncpy() function is similar, except that at most n bytes of src are copied. 除了最多复制n个src字节外,strncpy()函数与之类似。 Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated. 警告:如果src的前n个字节中没有空字节,则放置在dest中的字符串将不会以空值结尾。
Here is a substring function. 这是一个子字符串函数。 Don't forget to free the result when needed. 不要忘记在需要时释放结果。
/**
* Substrings in a new string, handles \0
* @param char* str , the string to substring
* @param int from , the start index included
* @param int count , the amount of characters kept
*/
char * strsubstr(char * str , int from, int count) {
char * result;
if(str == NULL) return NULL;
result = malloc((count+1) * sizeof(char));
if(result == NULL) return NULL;
strncpy(result, str+from, count);
result[count] = '\0';
return result;
}
At first you must understand some basic principles of c. 首先,您必须了解c的一些基本原理。
Scanf stops its %s
"string-reader" if it's read a space 如果Scanf读取了空格,则会停止其%s
“字符串读取器”
secondly you can read both of the strings in once. 其次,您可以一次读取两个字符串。 "%s %s" “%s%s”
at this case you do not need the action variable: 在这种情况下,您不需要action变量:
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char str1[2];
char str2[2];
scanf("%s %s",str1,str2);
return 0;
}
This way you take cover of the space termination and the pointers game.. 这样,您就可以掩盖空间终止和指针游戏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.