//Программа демонстрирует работу функций из файла stdlib.h
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
int main()
{
char sv[]="23.547",
si[]="1234",
sl[]="-112424",
st1[15],st2[25],st3[15];
double v;
int i;
long l,t=457821;
v=atof(sv);
printf("Преобразование строки в вещественное число = %f\n",v);
i=atoi(si);
printf("Преобразование строки в целое число = %d\n",i);
l=atol(sl);
printf("Преобразование строки в длинное целое число = %ld\n",l);
printf("Преобразование длинного целого числа в строку = %s\n",
ultoa(t,st1,10));
printf("Преобразование длинного целого числа в строку = %s\n",
ultoa(t,st2,2));
printf("Преобразование длинного целого числа в строку = %s\n",
ultoa(t,st3,16));
system("pause");
return 0;
}
Пример 8.
//Программа демонстрирует работу функций из файла string.h
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
int main(void)
{
char st[50],sp[100],str[]="",
si[]="qwerty",
sl[]="qwerty",
sw[]="qwertyu";
int len=0, sravn1, sravn2, sravn3, kol=5;
printf("Введите строку: ");
gets(st);
len=strlen(st); printf("Длина строки = %d\n",len);
printf("Конкатенация строк: %s\n",strcat(st,"12cdb"));
|
|
sravn1=strcmp(si,sl);
printf("Сравнение строк: %s==%s результат %d\n",
si,sl,sravn1);
sravn2=strcmp(si,sw);
printf("Сравнение строк: %s<%s результат %d\n",
si,sw,sravn2);
sravn3=strcmp(sw,si);
printf("Сравнение строк: %s>%s результат %d\n",
sw,si,sravn3);
printf("Копирование байтов: %s\n",strcpy(sp,st));
printf("Преобразование букв нижнего регистра в верхний: %s\n",
strupr(st));
printf("Преобразование букв верхнего регистра в нижний: %s\n",
strlwr(st));
printf("Копирование %d символов в другую строку: %s\n",
kol,strncpy(str,st,kol));
printf("Поиск в строке первого появления символа из другой строки:
%s\n",strpbrk(st,si));
printf("Поиск в строке последнее вхождение заданного
символа: %s\n",strrchr(st,'t'));
system("pause");
return 0;
}
Пример 9.
//Поиск множества неповторяющихся символов строки
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
int main(void)
{
char st[80];
int i,j,flag,len;
printf("Введите строку: ");
gets(st);
len=strlen(st); //длина строки
printf("Неповторяющиеся символы строки образуют множество: ");
for (i=0;i<len;i++){
flag=0; //флаг проверки на совпадение
for (j=0;j<i;j++) //сравнение символа с предыдущими
if (st[i]==st[j]) flag=1;
if (flag==0)printf("%c",st[i]);
}
system("pause");
return 0;
}
Пример 10.
/*Удаление лишних левых и внутренних пробелов в строке при выводе*/
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
int main(void)
{
char st[80];
int i=0,len;
printf("Введите строку: ");
gets(st);
len=strlen(st);//длина строки
printf("Преобразованная строка: ");
//Удалены лишние пробелы слева
while (st[i++]==' ');
//Удалены лишние пробелы внутри строки
for (--i;i<len;i++)
if ((st[i]!=' ')||(st[i+1]!=' '))
printf("%c",st[i]); //если рядом два пробела
system("pause");
return 0;
}
Для выполнения описанных в этом подразделе функций необходимо включить в программу файл string.h командой
|
|
#include <string.h>
strcat - сцепить две строки.
Определение: char *strcat(s1,s2)
char *s1, *s2;
Пример 11:
/* сцепить две строки */
/* в головном файле conio.h содержится функция очистки экрана clrscr() */
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
clrscr();
char destination[25];
char *blank = " ", *c = "C++", *turbo = "Turbo";
strcpy(destination, turbo);
strcat(destination, blank);
strcat(destination, c);
printf("%s\n", destination);
getch();
return 0;
}
strncat - сцепить две строки, причем из второй строки копировать не более n символов.
Определение: char *strncat(s1,s2,n)
char *s1, *s2;
int n;
Пример 12:
/* cцепить две строки, причем из второй строки
копировать не более n символов */
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
clrscr();
char destination[25];
char *source = "structured ";
strcpy(destination, "programming");
strncat(destination, source, 11);
printf("%s\n", destination);
getch();
return 0;
}
strcmp - сравнить две строки в лексикографическом порядке.
Определение: int strcmp(s1,s2)
char *s1, *s2;
Пример 13:
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{ char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc";
int ptr;
clrscr();
ptr = strcmp(buf2, buf1);
if (ptr > 0)
printf("buffer 2 is greater than buffer 1\n");
else
printf("buffer 2 is less than buffer 1\n");
ptr = strcmp(buf2, buf3);
if (ptr > 0)
printf("buffer 2 is greater than buffer 3\n");
else
printf("buffer 2 is less than buffer 3\n");
getch();
return 0;
}
strncmp - сравнить первые n символов двух строк.
Определение: int strncmp(s1,s2, n)
char *s1, *s2;
int n;
Пример 14:
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
char *buf1 = "aaabbb", *buf2 = "bbbccc", *buf3 = "ccc";
int ptr;
clrscr();
ptr = strncmp(buf2,buf1,3);
if (ptr > 0)
printf("buffer 2 is greater than buffer 1\n");
else
printf("buffer 2 is less than buffer 1\n");
ptr = strncmp(buf2,buf3,3);
if (ptr > 0)
printf("buffer 2 is greater than buffer 3\n");
else
printf("buffer 2 is less than buffer 3\n");
getch();
return(0);
}
strcpy - копировать строку s2 в строку s1.
Определение: char *strcpy(s1,s2)
char *s1, *s2;
Пример 15:
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void)
{
clrscr();
char string[10];
char *str1 = "abcdefghi";
strcpy(string, str1);
printf("%s\n", string);
getch();
return 0;
}
strncpy - копировать не более n символов строки s2.
Определение: char *strncpy(s1,s2,n)
char *s1, *s2;
int n;
Пример 6:
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void)
{
clrscr();
char string[10];
char *str1 = "abcdefghi";
strncpy(string, str1, 3);
string[3] = '\0';
printf("%s\n", string);
getch();
return 0;
}
strlen - определить длину строки (число символов без завершающего нулевого символа).
Определение: int strlen(s)
char *s;
Пример 17:
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void)
{
clrscr();
char *string = "Borland International";
printf("%d\n", strlen(string));
getch();
return 0;
}
strchr - найти в строке первое вхождение символа n.
Определение:
char *strchr(s,n)
char *s;
int n;
Пример 18:
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
clrscr();
char string[20];
char *ptr, c = 'r';
strcpy(string, "This is a string");
ptr = strchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr);
else
printf("The character was not found\n");
getch();
return 0;
}
strrchr - найти в строке последнее вхождение символа с.
Определение:
char *strrchr(s,c)
char *s;
int c;
Пример 19:
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
clrscr();
char string[20];
char *ptr, c = 'r';
strcpy(string, "This is a string");
ptr = strrchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, *ptr);
else
printf("The character was not found\n");
getch();
return 0;
}
strpbrk - найти в строке s1 любой из множества символов, входящих в строку s2.
Определение:
char *strpbrk(s1,s2)
char *s1, *s2;
Пример 20:
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void)
{
clrscr();
char *string1 = "abcdefghijklmnopqrstuvwxyz";
char *string2 = "onm";
int *ptr;
ptr = strpbrk(string1, string2);
if (ptr)
printf("strpbrk found first character: %c\n", *ptr);
else
printf("strpbrk didn't find character in set\n");
getch();
return 0;
}
strspn - определить длину отрезка строки s1, содержащего символы из множества, входящих в строку s2.
Определение:
int strspn(s1,s2)
char *s1, *s2;
Пример 21:
#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <conio.h>
int main(void)
{
clrscr();
char *string1 = "1234567890";
char *string2 = "123DC8";
int length;
length = strspn(string1, string2);
|
|
printf("Character where strings differ is at position %d\n", length);
getch();
return 0;
}
strcspn - определить длину отрезка строки s1, не содержащего символы cтроки s2.
Определение:
int strcspn(s1,s2)
char *s1, *s2;
Пример 22:
#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <conio.h>
int main(void)
{
clrscr();
char *string1 = "1234567890";
char *string2 = "747DC8";
int length;
length = strcspn(string1, string2);
printf("Character where strings intersect is at position %d\n", length);
getch();
return 0;
}
strtok - выделить из строки s1 лексемы, разделенные любым из множества символов, входящих в строку s2.
Определение: char *strtok(s1,s2)
char *s1, *s2;
Пример 23:
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
clrscr();
char input[16] = "abc,d";
char *p;
p = strtok(input, ",");
if (p) printf("%s\n", p);
p = strtok(NULL, ",");
if (p) printf("%s\n", p);
getch();
return 0;
}