UIU: Learn C by Examples : String


Program 1


#include <cstdio>

using namespace std;

int findLength (char *s)
{
    int ret = 0;

    while (*s != '\0') {
        ret++;
        s++;
    }

    return ret;
}

int main (int argc, char *argv [])
{
    char str [] = {"Program"};

    int length = findLength(str);

    printf ("%d\n", length);

    return 0;
}

Program 2


#include <cstdio>
#include <cstring>

using namespace std;

int main (int argc, char *argv [])
{
    char str1 [20] = "Hello";
    char str2 [20] = " World";

    printf ("%s\n", strcpy(str2, strcat(str1, str2)));

    return 0;
}

Program 3


#include <cstdio>

using namespace std;

int main (int argc, char *argv [])
{
    char p [] = "%d\n";

    printf (p, 65);

    p [1] = 'c';

    printf (p, 65);

    return 0;
}

Program 4


#include <cstdio>
#include <cstring>

using namespace std;

int main (int argc, char *argv [])
{
    char str [] = "Hello\0World\0";

    printf ("%s\n", str);

    printf ("%d\n", strlen(str));

    return 0;
}

Program 5


#include <cstdio>

using namespace std;

int main (int argc, char *argv [])
{
    char ch;

    while ( (ch = getchar()) != '\n' ) {
        printf ("%c", ch);
    }

    printf ("\n");

    return 0;
}

Program 6


#include <cstdio>
#include <cstring>

using namespace std;

int main (int argc, char *argv [])
{
    int num;

    scanf ("%d", &num);

    char str [100];

    gets(str);

    printf("%d %s\n", num, str);

    scanf ("%d", &num);

    getchar();

    gets(str);

    printf("%d %s\n", num, str);
    
    scanf ("%d", &num);

    scanf ("%s", str);

    printf("%d %s\n", num, str);

    return 0;
}

Program 7


#include <cstdio>
#include <cstring>

using namespace std;

int main (int argc, char *argv [])
{
    char str [] = "This";

    char str1 [] = "That";

    char str2 [] = "this";

    printf ("%d\n", strcmp(str, str1));

    printf ("%d\n", strcmp(str1, str2));

    printf ("%d\n", strcmp(str, str2));

    printf ("%d\n", strcmp(str, str));

    return 0;
}

Program 8


#include <cstdio>
#include <string>

using namespace std;

int main (int argc, char *argv [])
{
    // important string functions, you should know 
    strcat();
    strchr();
    strcmp();
    strcpy();
    strstr();
    strtok();

    return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s