C/String/String Split
Содержание
Add spaces to the end of a string
#include <stdio.h>
#include <string.h>
void pad(char *s, int length);
int main(void)
{
char str[80];
strcpy(str, "this is a test");
pad(str, 40);
printf("%d", strlen(str));
return 0;
}
void pad(char *s, int length)
{
int l;
l = strlen(s); /* its length */
while(l<length) {
s[l] = " "; /* insert a space */
l++;
}
s[l]= "\0"; /* strings need to be terminated in a null */
}
Replace space with dash
#include <stdio.h>
void sp_to_dash(const char *str);
int main(void)
{
sp_to_dash("this is a test");
return 0;
}
void sp_to_dash(const char *str)
{
while(*str) {
if(*str== " ")
printf("%c", "-");
else
printf("%c", *str);
str++;
}
}
Sequentially truncate string if delimiter is found
#include <stdio.h>
#include <string.h>
int main(void)
{
char *p;
p = strtok("The summer soldier, the sunshine patriot", " ");
printf(p);
do {
p = strtok("\0", ", ");
if(p) printf("|%s", p);
} while(p);
return 0;
}
Truncate string by delimiter: how to use strtok
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a sample string, just testing.";
char *p;
printf ("Split \"%s\" in tokens:\n", str);
p = strtok (str," ");
while (p != NULL)
{
printf ("%s\n", p);
p = strtok (NULL, " ,");
}
return 0;
}