#include "stdafx.h"
#include <string.h> //header for string manipulation
#include <cstdlib> //header for malloc
#define COL 300
bool sortStr(char(*str)[COL], int n)
{ //function to sort string array
if( str == NULL ) return false;
char tmp[COL];
for(int i=0; i<n-1; ++i)
{
for(int j=i+1; j<n; ++j)
{
if( strcmp(str[i], str[j]) > 0 )
{
strcpy_s(tmp, str[i]);
strcpy_s(str[i], str[j]);
strcpy_s(str[j], tmp);
}
}
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
int ncp = 4; //for string array
//dynamic allocation of string array
char(*str0)[COL] = (char(*)[COL])malloc(sizeof(char)*ncp*COL);
int id0 = 9, id1 = 12;
strcpy_s(str0[0], "s"); //input your string
strcpy_s(str0[1], "e");
char tmp[COL];
sprintf_s(tmp, "%d", id1); //input int value (id1) into string tmp
strcat_s(str0[0], tmp); //concatenate multiple strings into str[0]
sprintf_s(tmp, "%d", id0);
strcat_s(str0[1], tmp);
strcpy_s(str0[2], "e1");
strcpy_s(str0[3], "s2");
for(int i=0; i<ncp; ++i)
printf("str0[%d]:%s\n", i, str0[i]);
printf("--\n");
char(*str1)[COL] = (char(*)[COL])malloc(sizeof(char)*ncp*COL);
strcpy_s(str1[0], "e9");
strcpy_s(str1[1], "s12");
strcpy_s(str1[2], "e1");
strcpy_s(str1[3], "s3");
for(int i=0; i<ncp; ++i)
printf("str1[%d]:%s\n", i, str1[i]);
printf("\n=======compare=======\n");
printf("====before sorting===\n");
for(int i=0; i<ncp; ++i)
{
int res = strcmp(str0[i], str1[i]); //compare 2 strings value based on ASCII
printf("str[%d]: %d\n", i, res);
}
printf("\n=======sort=======\n");
if( sortStr(str0, ncp) == true )
{
for(int i=0; i<ncp; ++i)
printf("str0[%d]:%s\n", i, str0[i]);
}
printf("--\n");
if( sortStr(str1, ncp) == true )
{
for(int i=0; i<ncp; ++i)
printf("str0[%d]:%s\n", i, str1[i]);
}
printf("\n=======compare=======\n");
printf("====after sorting====\n");
for(int i=0; i<ncp; ++i)
{
int res = strcmp(str0[i], str1[i]);
printf("str[%d]: %d\n", i, res);
}
}
result
str0[0]:s12
str0[1]:e9
str0[2]:e1
str0[3]:s2
--
str1[0]:e9
str1[1]:s12
str1[2]:e1
str1[3]:s3
=======compare=======
====before sorting===
str[0]: 1
str[1]: -1
str[2]: 0
str[3]: -1
=======sort=======
str0[0]:e1
str0[1]:e9
str0[2]:s12
str0[3]:s2
--
str0[0]:e1
str0[1]:e9
str0[2]:s12
str0[3]:s3
=======compare=======
====after sorting====
str[0]: 0
str[1]: 0
str[2]: 0
str[3]: -1
No comments