Baja
Baja

Reputation: 55

How to split a string into characters of 2

For example Abraham Lincoln into AB, RA, HA ML, IN, CO, LN. Without using string.h or stdlib.h

#include <stdio.h>
int main ()
{
  printf("Enter the string: ");

  char inputstring[50];
  scanf("%[^\n]", inputstring);

  char *p = inputstring;
  char *k = inputstring;

  while (*p != '\0')
  {
    printf ("%c%c ", *p, *k);
    p++;
  }
  return 0;
}

Upvotes: 0

Views: 215

Answers (6)

0___________
0___________

Reputation: 67749

#include <stdio.h>
#define NULL ((void *)0)

char *mystrchr(const char *str, const char ch)
{
    char *result = NULL;
    if(str)
    {
        while(*str) 
        {
            if(*str == ch)
            {
                result = (char *)str;
                break;
            }
            str++;
        }
    }
    return result;
}

#define DELIM  " \n\r\t"

void printTwoChars(const char *str)
{
    const char *next;
    if(str && *str)
    {
        //skip leading whitespaces
        while(mystrchr(DELIM, *str)) str++;
        next = str + !!*str;
        while(*next)
        {
            if(!mystrchr(DELIM, *next)) 
            {
                printf("%c%c\n", *str, *next);
                str = next;
                next++;
            }
            else
            {
                next++;
            }
        }
    }
}

int main(void)
{
    char *str = "Margareth Tatcher";
    char initials[3];

    printTwoChars(str);
}

https://godbolt.org/z/vWPbfz

Upvotes: 0

Agus
Agus

Reputation: 689

Based on the problem statement, need to:

  1. Create a function similar to toUpper().
  2. Handle only non-space characters.
  3. Handle odd number non-space characters.
  4. Formatting, i.e. add ', ' only for non-first pair


Below is the output sample of the following code

Enter the string: abraham lincoln
AB, RA, HA, ML, IN, CO, LN
Enter the string: abcde fghijk
AB, CD, EF, GH, IJ, K

Code:

#include <stdio.h>

char myToUpper(char c) {
    if(c >= 97 && c <= 122) {
        c = c-32;
    } //end if
    return c;
}

int main(void) {
    printf("Enter the string: ");
    char inputstring[50] = {0};
    scanf("%[^\n]", inputstring);

    char *p = inputstring;
    int counter=0;
    char firstChar, secondChar;
    int isFirstPair = 1; //this is to handle the flag for first pair, used as the counter for comma character (only first pair do not need comma)
    while (*p != 0) {
        //this is to change between state (1st and 2nd character), need to exclude space
        if (*p != ' ') { //only process non-space character, you can add more character filtering if needed
            if (counter == 0) { //first char
                firstChar = *p;
                counter=1;
            } else  { //if we are on the 2nd character, then capitalize it and print it (along with the comma if needed)
                secondChar = *p;

                if (isFirstPair == 1) {
                    isFirstPair = 0;
                } else {
                    printf(", ");
                } //end else

                printf("%c%c", myToUpper(firstChar), myToUpper(secondChar));
                counter=0;
            } //end else
        } //end if
        p++;
    } //end while

    //this is to handle when there are odd number of non-space characters
    if (counter  == 1) {
        if (isFirstPair == 1) { //this is for the case where there is only 1 character input
            printf("%c", myToUpper(firstChar));
        } else {
            printf(", %c", myToUpper(firstChar));
        } //end else
    } //end if

    return 0;
}

Upvotes: 1

hafiz031
hafiz031

Reputation: 2710

Alright! First I want to say that, there are many corner cases in this problem which must be covered (according to the sample input and output), like:

  • Eliminating the spaces even if there are any.
  • Capitalizing the characters.
  • Putting a comma after each of the paired characters, followed by a space (except the last pair).
  • For the last pair there will be just a full-stop and no space after that.
  • Also the capability to handle odd-length input (excluding spaces and newline). I am assuming at least one non-space and non-newline printable character will be in the input.

All of these cases are covered in the following implementation. Hope you like it:

#include <stdio.h>

int main ()
{
    printf("Enter the string: ");

    char inputstring[50];
    scanf("%[^\n]", inputstring);

    // THE COMPLETE TASK CAN BE PERFORMED IN 3 STEPS.

    // STEP: 1
    // Remove spaces from the input.
    int j = 0;
    for(int i = 0; inputstring[i] != '\0'; i++)
    {
        if(inputstring[i] != ' ')
        {
            inputstring[j++] = inputstring[i];
        }
    }

    // Setting the new termination of the string after a possible removal of spaces.
    // Even if there are no spaces it is still okay. As j is also incrementing.
    inputstring[j] = '\0';


    // STEP: 2
    // Capitalization.
    for(int i = 0; inputstring[i] != '\0'; i++)
    {
        // If current character in the input string is lower-case,
        // make it upper-case.
        // In ASCII table, the upper-cases [A-Z] are 32 steps behind than their counter lower-cases [a-z].
        if(inputstring[i] >= 'a' && inputstring[i] <= 'z')
        {
            inputstring[i] = inputstring[i] - 32;
        }
    }


    // STEP: 3
    // Initialize two pointers based on even and odd positions.
    // Remember! Counting from 0, hence the 1st position is even
    // and the 2nd position is odd and so on.
    char *even_positioned_pointer = inputstring;
    char *odd_positioned_pointer = inputstring + 1;

    // Print it!
    // As even is behind than odd position (using 0 based indexing),
    // hence, *even_positioned_pointer == '\0' means the string is over.
    // So, looping until it is NOT '\0'.
    while(*even_positioned_pointer != '\0')
    {
        printf("%c", *even_positioned_pointer);

        // It might be the case that the final even_positioned_pointer doesn't have its odd counterpart.
        // This happens when the inputstring's length is odd.
        if(*odd_positioned_pointer != '\0')
        {
            printf("%c", *odd_positioned_pointer);
        }
        else
        {
            // Put a full-stop.
            printf(".");
            break;
        }

        // If the current *even_positioned_pointer is the last character,
        if(*(odd_positioned_pointer + 1) == '\0')
        {
            // then put a full-stop.
            printf(".");
        }
        else
        {
            // Otherwise, put a comma followed by a space.
            printf(", ");
        }

        // To keep the even_positioned_pointer at even position.
        // Same goes to odd_positioned_pointer.
        even_positioned_pointer += 2;
        odd_positioned_pointer += 2;
    }

    return 0;
}

 

Upvotes: 2

William Pursell
William Pursell

Reputation: 212404

It depends on what you want. If you want to create null-terminated arrays with strlen(2), you'll need to make copies. But if you just want to write the data, you could get away with something like:

#include <stdio.h>

int
main(int argc, char **argv)
{
        const char *s = argc > 1 ? argv[1] : "Abraham Lincoln";
        const char *p = s;
        while( p[0] && p[1] ){
                fwrite(p, 1, 2, stdout);
                putchar('\n');
                p += 2;
        }
        if( p[0] ){
                fwrite(p, 1, 2, stdout);
                putchar('\n');
        }
        return 0;
}

Upvotes: 0

random
random

Reputation: 55

a working solution without extra functions , you can replace len with strlen from string.h later if you decide to.

#include <stdio.h>

int len(const char *str){
    unsigned long int i = 0;
    while(1){
        if (str[i] != '\0'){
            i++;
        }else{return i;}
    }
}

int main ()
{
  char string[50];

  printf("Enter the string : ");
  gets(string);
  if( len(string) % 2 == 0 ){
    for(unsigned int i = 0 ; i < len(string) ; i = i + 2){
        printf("%c%c " , string[i] , string[i+1]);
    }
  }
  return 0;
}

Upvotes: 1

Victor
Victor

Reputation: 428

I think the most comprehendible way here would be to write a function which returns you the next character of a string (you may need to skip spaces, so separating this logic into a function will probably be handy), and then just call this function 2 times in a loop until the string ends.

Upvotes: 1

Related Questions