this is my first question on stack and I'm beginner in c.I declared a char array a[100]={"this is a test\n2nd test}.Now I'm trying to divide this array and take the two parts before and after \n as separate strings.So I declared a 2d array ab[i][k] and used a for loop to copy the characters to ab[i]. if a[j]=='\n', I put a NULL character at the current position of ab[i][k] and increment i by 1.But for some reason, both ab[0] and ab[1] are displaying "this is a test" when I used printf to display them.Any help or suggestions would be appreciated.
int i=0;
char a[100],ab[100][100],c;
fputs(a,stdout);
printf("%d ",strlen(a));
for(j=0;j<=strlen(a);j++,k++)
{
if(a[j]=='\n')
{
ab[i][k]='\0';
k=0;
i++;
continue;
}
ab[i][k]=a[j];
}
printf("%s\n",ab[0]);
printf("%s",ab[1]);
You need to set k=-1;
when you find \n
, since it will be incremented at the top of the loop to 0
when you continue;
.
You also need to declare int j, k=0;
before the loop, to get your code to compile.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[]) {
int i=0;
char ab[100][100];
char a[100] = "this is a test\n2nd test";
printf("%d \n",strlen(a));
int j, k=0;
for(j=0; j<=strlen(a); j++,k++) {
if(a[j]=='\n') {
ab[i][k]='\0';
k=-1;
i++;
continue;
}
ab[i][k]=a[j];
}
printf("1: %s\n",ab[0]);
printf("2: %s\n",ab[1]);
return 0;
}
23
1: this is a test
2: 2nd test
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char ar[100] = "this is a test\n2nd test\nfoobar\netc";
char sep[10][100];
int i=0;
char* token = strtok(ar, "\r\n");
while(token != NULL) {
sprintf(sep[i], "%s", token);
printf("string #%02i: `%s`.\n", i, sep[i]);
token = strtok(NULL, "\r\n");
i++;
}
return 0;
}
strtok()
splits a string by any of the characters passed as a delimiter (new line and carriage return, in this case) into tokens. Passing a null pointer to the function continues where it last left off. It returns a pointer to the beginning of the token,
sprintf()
saves formatted data into a variable handling \0 for you, but you could also use memcpy()
or strcpy()
if you like.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.