How To Convert String To Character In C

A string is a group of characters that ends with the null character “\0” in C programming. A char is a data type for single characters. The process of converting a string to a char array involves copying the string’s characters to the array. When using functions that require a char array or when converting a string to a format that can be readily saved or transferred, this is frequently required.

In this article, we’ll explore 5 conversion methods for string to char conversion in C and contrast their benefits with their drawbacks.

Why is there a need to convert string to character in C?

Several circumstances call for the ability to convert a string to a character in C. Here are some instances in which it may be essential to translate a string into a character:

  1. Manipulation: In C, it may be necessary to access a single character in a string when doing string manipulation.
  2. File I/O: In order to carry out certain operations when reading or writing to a file, we might need to extract a specific character from a string.
  3. Encryption: In order to carry out specified actions, several encryption methods call for converting a string to a character.
  4. Password validation: In order to execute specified activities, it can be essential to remove a single character from a string while validating passwords.
  5. Network protocol: In order to carry out specific operations, it can be essential to extract a single character from a string when working with network protocols. To validate the reliability of the information, for instance, while utilising the TCP/IP protocol, we might need to extract the checksum character.

In some cases, it could be necessary to convert a string to a char array in order to carry out specific data operations or manipulations, such as sorting or searching. Moreover, working with char arrays can be easier and more memory-efficient, particularly for large datasets.

Approaches :

  1. Using array subscripting.
  2. Using pointer arithmetic.
  3. Using library functions.
  4. Using the ‘sscanf()’ function.
  5. Using the ‘strtok()’ function.

Approach 1 : Using array subscripting

This method accesses each character in the string via array subscripting. We can use a loop to extract each character from the string by iterating through it using its index. This strategy is simple and basic.

An advantage of implementing array subscripting to transform a string into a character array is that it is an easy and understandable process. For programmers who are familiar with C arrays, it is simple to comprehend and use. It is also a rather effective technique in terms of time complexity.

The disadvantage of utilising array subscripting is that there is no built-in method for checking boundaries. This means that if insufficient space is allotted for the character array, buffer overflow and other memory-related problems may result.

This method’s time complexity may be expressed as O(n).

Code :

#include <stdio.h>

int main() {
	char str[] = "GeeksForRescue";
	int i;

	for (i = 0; str[i] != '\0'; i++) {
    	printf("%c ", str[i]);
	}

	return 0;
}

Output :

G e e k s F o r R e s c u e

Code Explanation :

  1. The program contains the “stdio.h” standard input/output header file.
  2. The main() function, which returns an integer value, is declared in the program.
  3. The program declares the value “Thanks for the help” in the char array “str”.
  4. The program declares a loop counter, “i” which is an integer variable.
  5. The for loop, which starts with the loop counter “i” initialised to 0, checks to see if the character at index i in the “str” array is not the null character “\0,” and increments “i” by 1 after each iteration, is then started.
  6. The printf() function with the “%c” format specifier is used in the for loop’s body to print the character at index i of the “str” array.
  7. When the program comes across the null character “\0” in the “str” array, the for loop is terminated.
  8. To signify that the main() function has been successfully completed, the program returns 0.

Approach 2 : Using pointer arithmetic

Pointer arithmetic is used to gain access to each character in the string. You can use a pointer to the beginning of the string and increase it until it reaches the end. This approach is likewise straightforward and simple to comprehend, but because pointer arithmetic adds overhead, it may not be as effective as array subscripting.

The disadvantage of this technique is that it can be more difficult to study and understand than array subscripting. The pointer can also result in memory access issues like segmentation faults if it is not handled appropriately.

This method’s time complexity may be expressed as O(n).

Code :

#include <stdio.h>

int main() {
	char str[] = "Geeks For Rescue";
	char *ptr = str;

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

Output :

G e e k s   F o r   R e s c u e

Code Explanation :

  1. The header file “stdio.h” from the standard input/output library is included in the code.
  2. It is specified that the primary function returns the integer value 0.
  3. The string “Thanks for the help” is declared and initialised in the character array “str.”
  4. The first element of the “str” array is the target of the character pointer “ptr,” which is declared and initialised.
  5. The string is iterated over until the null character ‘\0’ is reached using a while loop. The loop condition determines whether the current character, as indicated by “ptr,” does not have a value that is equal to the null character “\0.”
  6. The printf() function inside the loop prints the character pointed to by “ptr” at that moment using the %c format specifier.
  7. The next character in the string is indicated by incrementing the pointer “ptr” once the character has been printed.
  8. The loop ends when the main function encounters the null character “\0,” returning 0.

Approach 3 : Using library functions

In C, you can use predefined library functions like ‘strcpy()’ and ‘strncpy()’ to convert a string to a character array or char pointer (). These functions make string manipulation in C simple and efficient.

To copy a string from one character array to another, use the ‘strcpy()’ function. It accepts two arguments: the source string and the destination character array. The function appends a null character to the destination string.

In this case, The ‘strncpy()’ function is similar to ‘strcpy()’.This can help to avoid buffer overflow errors. Three arguments are passed to the function: the destination character array, the source string, and the maximum number of characters to copy. The function appends a null character to the destination string. ‘strncpy()’ has the advantage of preventing buffer overflow errors.

Code :

# Convert an integer to bytes using the bytearray() method
num = 255
byte_array = bytearray(num.to_bytes(2, byteorder='big'))

# Print the byte array and its type
print(byte_array)
print(type(byte_array))

Output:

H o w   t o   c o n v e r t   s t r i n g   i n t o   c h a r a c t e r   i n   C   l a n g u a g e !

Code Explanation :

  1. The program’s entry point, where execution starts, is the main() function.
  2. Using the char data type, a character array “str” of size 100 is declared, and it is initialised with a lengthy string containing details about Conversion of String in Character.Another char array of 100 characters is declared.
  3. The size of char array minus 1 is the maximum length of characters that can be copied when using the “strncpy()” method to transfer the contents of the “str” array to char array (to allow space for the null terminator).
  4. With the assignment operator, the null terminator is inserted to the end of the char array.
  5. The characters in char array are iterated over in a for loop until the null terminator is reached.
  6. The printf() function and the %c format specifier are used inside the loop to print each character from the char array to the console.
  7. The return statement is then used to finish the programme and provide the calling process the integer value 0.

For converting a string to a char array, you can alternatively utilise other library functions like sprintf(). While a string can be formatted and stored in a character array using the sprintf() function.

Approach 4 : Using the “sscanf()” function

In C, the ‘sscanf()’ function is used to read formatted input from a string.

The benefit of using ‘sscanf()’ to convert a string to a char array is that it is a standard library function, which means it is portable across platforms.

The use of ‘sscanf()’ has the disadvantage of being slower than other methods, especially when dealing with large input strings.

This method’s time complexity may be expressed as O(n).

Code :

#include <stdio.h>
#include <string.h>
int main() {
	char str[] = "GeeksForRescue";
	char ch;
	sscanf(str, "%c", &ch);
	// Here only one character is been printed
	printf("%c\n", ch);
	return 0;
}

Output :

G

Code explanation :

  1. The program’s entry point, where execution starts, is the main() function.
  2. A character array str of size 14 is declared and initialised with the text “Thanks for the help” using the char data type.
  3. char variable is defined as “ch”.
  4. The first character of the string str is read using the sscanf() method, and it is then saved in the ch variable. Similar to the scanf() function, the sscanf() function parses a string and reads data from it.
  5. One character should be input, as indicated by the “%c” format specifier.
  6. The ch variable’s memory address is passed to the sscanf() method via the & operator so that the value may be stored there.
  7. The character that is kept in the ch variable is printed using the printf() function.
  8. The code receives 0 as a result of the program’s successful conclusion.

Approach 5 : Using the “strtok()” function.

The ‘strtok()’ function in the C, is used to tokenize a string into smaller strings based on a delimiter. It is a common method of converting string to char in C with ease.

The main advantage of this method is, it comes predefined in C library i.e. no additional coding is required. It also provides a quick and efficient way to tokenize a string and convert it to a character array.

The drawback of using ‘strtok()’ is that it modifies the original string by inserting null characters at delimiter positions. This can cause problems later on when working with the original string.

This method’s time complexity may be expressed as O(n).

Code :

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Geeks for rescue";
    char *token;

    token = strtok(str, "");
    while (token != NULL) {
        for (int i = 0; i < strlen(token); i++) {
            printf("%c ", token[i]);
        }
        printf("\n");
        token = strtok(NULL, "");
    }
    return 0;
}

Output:

G e e k s   F o r   R e s c u e

Code explanation :

  1. The program’s entry point, where execution starts, is the main() function.
  2. The string str of size 20 is declared using the char data type, and it is initialised with the string “Thanks for the help”
  3. The individual characters from the string will be stored in a 20 × 20 2D character array named char array.
  4. The str string is divided into tokens by the strtok() function and separated by commas. The split string and the delimiter are provided as the first and second arguments, respectively, to strtok().
  5. In order to keep track of the number of tokens, an integer variable named I is initialised to zero.
  6. To iterate through the tokens obtained by “strtok()”, use a while loop (). Up until there are no more tokens left, the loop continues.
  7. Tokens are copied one at a time to the char_array array using the strcpy() method. The source string is the second input to strcpy(), and the destination character array is the first.
  8. The strtok() function is called once more with the first argument set to NULL to retrieve the next token after copying each token.
  9. After each token is copied to the char array, the loop counter I is increased.
  10. The printf() function is then used in a for loop to cycle through the characters in the char array and output each character to the console.
  11. The program is terminated and the integer value 0 is returned to the calling process using the return command.

Best Approach

Approach : Using pointer arithmetic method.

By using pointers, we may access the characters directly in the original string without incurring the overhead of duplicating the full string to a character array. When we wish to alter the characters in the string without changing the original string, this method can also be useful.

  • Efficiency: The direct manipulation of string pointers used in the pointer arithmetic approach is very efficient in terms of memory usage and execution time.
  • Flexibility: The pointer arithmetic method offers the programmer a great deal of flexibility since it enables pointer dereferencing, which lets him directly alter the characters in a string.
  • Dynamic Memory Allocation: With dynamically allocated strings, such as those produced by the malloc() function, this strategy can also be applied.
  • Simplicity: The implementation of the pointer arithmetic approach is also quite straightforward since it simply calls for the usage of fundamental pointer arithmetic operations such as pointer addition, subtraction, and dereferencing.
  • Time Complexity: O(n) is the time complexity. The time complexity of the other methods, such as the use of library functions like strcpy() or strtok(), is the same as this (). Yet, since the pointer arithmetic method directly modifies memory locations, it might actually be a little quicker in use than other methods that call functions.

Sample Problems

Sample Problem 1 :

Consider creating a programme that reads a file containing a list of words and determines whether or not each word is a palindrome. You must have access to a word’s component characters to determine if it is a palindrome.

Solution :

  • The program’s entry point, the main() function, is defined.
  • “word” is a character array with a maximum character capacity of 100.
  • Declared are the integers i ,j, len, and isPalindrome. These variables will be applied to the string to determine its length, iterate through it, and determine whether it is a palindrome.
  • The scanf() function is then used by the software to read a word from the user and place it in the word character array.
  • The strlen() function is then used to calculate the length of the string, and the result is saved in the len variable.
  • The word is first presumed to be a palindrome since the software initialises the isPalindrome variable to 1, or 1.
  • The code then iterates over the string in a for loop, comparing the characters at the start and end to see if the string is a palindrome. In order to access the individual characters in the string, array subscripting is used.
  • The isPalindrome variable is set to 0, indicating that the word is not a palindrome, if a character at the beginning of the string does not match the equivalent character at the end of the string.
  • The output of the programme then uses printf() to show the original word and whether or not it is a palindrome.
  • Following that, the main() function returns 0, indicating that the code ran correctly.

Code:

#include <stdio.h>
#include <string.h>

int main() {
   char word[100];
   int i, j, len, isPalindrome;

   printf("Enter the String : ");
   scanf("%s", word);
   len = strlen(word);
   isPalindrome = 1;
   for (i = 0, j = len - 1; i < len / 2; i++, j--) {
      if (word[i] != word[j]) {
         isPalindrome = 0;
         break;
      }
   }
   if (isPalindrome) {
      printf("%s is a Palindrome String.\n", word);
   } else {
      printf("%s is not a Palindrome String.\n", word);
   }

   return 0;
}

Output:

Enter the String : BIIB
BIIB is a Palindrome String.

Sample Problem 2 :

An organisation wishes to keep employee information such as name, age, pay, and employee ID. The data must be saved in a way that makes it simple to retrieve and modify. Also, the organisation must have the ability to look up employees using their IDs.

Solution :

  • Using a struct to store the employee data and an array of pointers to the struct to store the employee records is one way to solve this issue. Each employee’s ID can be used as an index into the array to find their record by using the array as a whole.
  • Create the struct Employee to hold an employee’s information, such as name, age, pay, and ID.
  • Declare an array of 5 employee records and an array of 5 pointers to employee records in the main function.
  • By requesting the user’s input for each employee’s name, age, salary, and ID, utilise a for loop to populate the employee records and pointers. Put the arrow where it belongs—on the personnel record.
  • Get the user’s input for the ID to search for.
  • Create a second for loop to check each employee record’s ID using the pointers, then look for the employee record with the matching ID. A pointer to the employee record with the matching ID should be assigned to a result variable, and the loop should be broken, if it is discovered.
  • Verify that the outcome variable is not NULL. Print the employee record’s details if it is not NULL. If not, print a message stating that the employee could not be located.
  • To show that the code has run successfully, return 0.

Code :

#include <stdio.h>
#include <stdlib.h>

struct Employee {
    char name[50];
    int age;
    float salary;
    int id;
};

int main() {
    struct Employee employees[5];
    struct Employee *ptrs[5];
    for (int i = 0; i < 5; i++) {
        printf("Enter the Employee name: ");
        scanf("%s", employees[i].name);
        printf("Enter the Employee age: ");
        scanf("%d", &employees[i].age);
        printf("Enter the Employee salary: ");
        scanf("%f", &employees[i].salary);
        printf("Enter the Employee ID: ");
        scanf("%d", &employees[i].id);
        ptrs[i] = &employees[i];
    }
    int search_id;
    printf("Enter ID to search for: ");
    scanf("%d", &search_id);

    struct Employee *result = NULL;
    for (int i = 0; i < 5; i++) {
        if (ptrs[i]->id == search_id) {
            result = ptrs[i];
            break;
        }
    }

    if (result != NULL) {
        printf("Employee found:\n");
        printf("Name: %s\n", result->name);
        printf("Age: %d\n", result->age);
        printf("Salary: %f\n", result->salary);
        printf("ID: %d\n", result->id);
    } else {
        printf("Employee not found.\n");
    }

    return 0;
}

Output :

Enter the Employee name: John
Enter the Employee age:14
Enter the Employee salary: 5000
Enter the Employee ID: 1
Enter the Employee name: David
Enter the Employee age: 40
Enter the Employee salary: 8000
Enter the Employee ID: 2
Enter the Employee name: Anna
Enter the Employee age: 20
Enter the Employee salary: 5400
Enter the Employee ID: 3
Enter the Employee name: Gabriel
Enter the Employee age: 42
Enter the Employee salary: 8500
Enter the Employee ID: 4
Enter the Employee name: Lucy
Enter the Employee age: 25
Enter the Employee salary: 7500
Enter the Employee ID: 5

Enter ID to search for: 1
Employee found:
Name: John
Age: 14
Salary: 5000.000000
ID: 1

Sample Problem 3:

John has a project that calls for you to get information from a database and put it in a character array. The data is returned by the database as a string, thus you must convert it to a character array before processing it further.

Given text : How to convert String to char in C Language!

Solution :

  1. The program’s entry point, where execution starts, is the main() function.
  2. Using the char data type, a character array “str” of size 100 is declared, and it is initialised with a lengthy string containing details about Conversion of String in Character.Another char array of 100 characters is declared.
  3. The size of char array minus 1 is the maximum length of characters that can be copied when using the “strncpy()” method to transfer the contents of the “str” array to char array (to allow space for the null terminator).
  4. With the assignment operator, the null terminator is inserted to the end of the char array.
  5. The characters in char array are iterated over in a for loop until the null terminator is reached.
  6. The printf() function and the %c format specifier are used inside the loop to print each character from the char array to the console.
  7. The return statement is then used to finish the programme and provide the calling process the integer value 0.

Code :

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "How to convert string into character in C language!";
    char char_array[100];
    strncpy(char_array, str, sizeof(char_array) - 1);
    char_array[sizeof(char_array) - 1] = '\0';
    for (int i = 0; char_array[i] != '\0'; i++) {
        printf("%c ", char_array[i]);
    }
    return 0;
}

Output:

H o w   t o   c o n v e r t   s t r i n g   i n t o   c h a r a c t e r   i n   C   l a n g u a g e !

Sample problem 4 :

Consider creating a software that reads information from a CSV file that has a list of employee details. The name and age of each employee are listed on a distinct line in the file, separated by a comma.

Given data : Leo Messi,35

Solution :

  1. The name and age are being extracted from the string str in this example using the sscanf() function from the C standard library.
  2. The name and age values in the string are separated by commas, and the format string “%[^,],%d” is used to match them.
  3. Any character that is not a comma is matched by the%[^,] specifier, and the resulting characters are saved in the name character array.
  4. To match the separator between the name and age values, a comma (), is used.
  5. The%d specifier stores the age value in the variable age when it matches the age value.
  6. printf is used to output the extracted name and age information to the console().

Code :

#include <stdio.h>
int main() {
   char str[] = "Leo Messi,35";
   char name[10];
   int age;
   
   sscanf(str, "%[^,],%d", name, &age);
   
   printf("The original string is: %s\n", str);
   printf("The name is: %s\n", name);
   printf("The age is: %d\n", age);
   
   return 0;
}

Output :

The original string is: Leo Messi,35
The name is: Leo Messi
The age is: 35

Sample Problem 5 :

Consider creating a program that pulls data from a text file containing a list of product specifications. The name, price, and description of each product are listed separately on each line of the file, followed by a comma.

Given : “MSI GL 65 Leopard, Rs 1,20,000, The best Gaming Laptop.”

Solution :

  1. In this example, the product name is extracted from the string str using the strtok() function from the C standard library.
  2. The delimiter character “,” designating the place where the string should be split, and the input string str are both required arguments for the function.
  3. The “MSI GL 65 Leopard” brand name is the first token that the strtok() method locates in the string, which is returned as a pointer by the function.
  4. The token is copied to a character array called name using the strcpy() function so that it can be used for later processing.
  5. Using printf, the extracted product name is displayed on the console().

Code :

#include <stdio.h>
#include <string.h>

int main() {
   char str[] = "MSI GL 65 Leopard, Rs 1,20,000, The best Gaming Laptop.";
   char *token;
   char name[20];
   
   // extract the product name from the string
   token = strtok(str, ",");
   strcpy(name, token);
   
   printf("The product name is: %s\n", name);
   
   return 0;
}

Output :

The product name is: MSI GL 65 Leopard

Conclusion

In conclusion we can see there are various methods for converting  String to Char in C i.e. it can also be done with the help of predefined functions. The method’s effectiveness depends on its flexibility, simplicity, time complexity and other factors similar to these.

While efficient and simple, pointer arithmetic and array subscripting involve explicit memory allocation and have the potential to cause buffer overflow issues. Although secure and practical, library functions like strncpy() may not necessarily be the most effective.

Although it can be slower and more difficult to use, sscanf() is useful for converting text with sophisticated formatting. Last but not least, the strtok() function can be used to split a string into smaller chunks, however it alters the original text and can be challenging to utilize in some circumstances.

Generally, the most effective method to employ relies on the precise specifications of the current task. When choosing a method to convert a string to a char in a programming language, it’s crucial to take into account elements like effectiveness, safety, and convenience of usage.