I am trying to write a function that changes all lowercase letters of a string to uppercase. Here is my code:
/**
* string_toupper - This function will replace all lowercase letters in
* the string pointed by str to uppercase
* #str: The string that will be checked for lowercase letters
*
* Return: The resulting string str, where all the letters are uppercase
*/
char *string_toupper(char *str)
{
int i;
for (i = 0; *str != '\0'; i++)
{
if (str[i] >= 'a' && str[i] <= 'z')
str[i] -= 32;
}
return (str);
}
And I tried it using:
#include <stdio.h>
int main(void)
{
char str[] = "Hello World!\n";
char *ptr;
ptr = string_toupper(str);
printf("%s\n", ptr);
printf("%s\n", str);
return (0);
}
But I get the following output:
Segmentation fault(core dumped)
My approach --> I will check the string if it has a lowercase letter. Then I will subtract 32 from the character if it matches to a lowercase character. I did this to make the character to uppercase, by subtracting 32 I am able to get the uppercase letter of the corresponding lowercase character I have found in the string.
But I am getting a Segmentation fault error, why is it happening?
change the for loop condition to for (i = 0; str[i] != '\0'; i++) since it should check every index.
char *string_toupper(char *str)
{
int i;
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] >= 'a' && str[i] <= 'z')
str[i] =(int)str[i] - 32;
}
return (str);
}
By request, this is offered for education and debate.
Some workplaces or institutes insist on a particular style wrt curly braces, etc. I freelance...
Notice that the function name is not reproduced in a comment block. Bad habit that leads to satisfying supervisors with copy/paste of comment blocks that are WRONG and certainly misleading. Better to let the code explain itself by using conventional idioms and standard libraries.
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
char *string_toupper( char *str ) {
// Uppercase all lowercase letters found in 'str'.
// Return str after processing.
assert( str != NULL ); // Trust no-one, especially yourself
// Alternative for():: for( int i = 0; str[ i ]; i++ )
for( int i = 0; str[ i ] != '\0'; i++ )
str[ i ] = (char)toupper( str[ i ] ); // note casting.
return str;
}
int main( void ) {
char str[] = "Hello World!";
// No further use? Don't store return value; just use it.
printf( "%s\n", string_toupper( str ) );
printf( "%s\n", str );
return 0;
}
OP's key problem is well explained by Prithvish: wrong loop test.
// for (i = 0; *str != '\0'; i++)
for (i = 0; str[i] != '\0'; i++)
To help OP with How can I make my code work on every environment?, some thoughts for later consideration.
Future names
"Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header." C17dr § 7.31.13
So do not code function names that begin str<lowercase> to avoid future collisions.
Indexing type
int i; is too narrow a type for long lines. Use size_t for array indexing.
Alternatively simply increment the pointer.
Test case with classification is...() functions
str[i] >= 'a' && str[i] <= 'z' is incorrect on systems where [a...z] are not continuous. (Uncommon these days - example EBCDIC).
Simplify with topper()
To convert any character to its uppercase equivalent:
str[i] = toupper(str[i]);
Use unsigned access
is..(x) and toupper(x) functions need unsigned char character values (or EOF) for x.
On soon to be obsolete rare non-2's complement systems, character string should be accessed as unsigned char to avoid stopping on -0.
Putting this together:
#include <ctype.h>
char *str_toupper(char *str) {
unsigned char *ustr = (unsigned char *) str;
while (*ustr) {
*ustr = toupper(*ustr);
ustr++;
}
return str;
}
There is a major mistakes in your code:
the test in for (i = 0; *str != '\0'; i++) in function string_toupper is incorrect: it only tests the first character of str instead of testing for the end of string. As coded, you keep modifying memory well beyond the
end of the string until you reach an area of memory that cannot be read or written, causing a segmentation fault. The code has undefined behavior. You should instead write:
for (i = 0; str[i] != '\0'; i++)
Also note that if (str[i] >= 'a' && str[i] <= 'z') assumes that the lowercase letters form a contiguous block in the execution character set. While it is the case for ASCII, you should not make this assumption in portable code.
Similarly, str[i] -= 32; is specific to the ASCII and related character sets. You should either use str[i] = str[i] - 'a' + 'A'; which is more readable or use the functions from <ctype.h>.
Here is a modified version:
#include <stdio.h>
/**
* string_toupper - This function will replace all lowercase letters in
* the string pointed by str with their uppercase equivalent
* #str: The string that will be checked for lowercase letters
*
* Return: The resulting string str, where all the letters are uppercase
*/
char *string_toupper(char *str) {
for (size_t i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'a' && str[i] <= 'z')
str[i] = str[i] - 'a' + 'A';
}
return str;
}
int main() {
char str[] = "Hello World!\n";
char *ptr;
printf("before: %s\n", str);
ptr = string_toupper(str);
printf("result: %s\n", ptr);
printf(" after: %s\n", str);
return 0;
}
And here is a portable version of string_toupper():
#include <ctype.h>
#include <stddef.h>
char *string_toupper(char *str) {
for (size_t i = 0; str[i] != '\0'; i++) {
if (islower((unsigned char)str[i]))
str[i] = (char)toupper((unsigned char)str[i]);
}
return str;
}
Related
I need to build a function that gets an input and capitalizes only the first letter, doesn't print numbers, capitalizes after a . for a new sentence, and capitalizes all words between a double quotation marks ".
This is what I got until now:
#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX] = { 0 };
int i;
//input string
printf("Enter a string: ");
scanf("%[^\n]s", str); //read string with spaces
//capitalize first character of words
for (i = 0; str[i] != '\0'; i++)
{
//check first character is lowercase alphabet
if (i == 0)
{
if ((str[i] >= 'a' && str[i] <= 'z'))
str[i] = str[i] - 32; //subtract 32 to make it capital
continue; //continue to the loop
}
if (str[i] == '.')//check dot
{
//if dot is found, check next character
++i;
//check next character is lowercase alphabet
if (str[i] >= 'a' && str[i] <= 'z')
{
str[i] = str[i] - 32; //subtract 32 to make it capital
continue; //continue to the loop
}
}
else
{
//all other uppercase characters should be in lowercase
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] = str[i] + 32; //subtract 32 to make it small/lowercase
}
}
printf("Capitalize string is: %s\n", str);
return 0;
}
I cant find a way to remove all numbers from input and convert all lowercase to uppercase inside a " plus code for not printing numbers if user input them.
if I input
I am young. You are young. All of us are young.
"I think we need some help. Please" HELP. NO, NO NO,
I DO NOT
NEED HELP
WHATSOEVER.
"Today’s date is
15/2/2021"...
I am 18 years old, are you 20 years old? Maybe 30 years?
output:
I am young. You are young. All of us are young.
"I THINK WE NEED SOME HELP. PLEASE" help. No, no no,
i do not
need help
whatsoever.
"TODAY’S DATE IS
//"...
I am years old, are you years old? maybe years?
The C standard library provides a set of functions, in ctype.h, that will help you
Of particular interest, would be:
isdigit() - returns true if digit
isalpha() - returns true if alphabet character
isalnum() - returns true if alpha/numeric character
islower() - returns true if lower case character
isupper() - returns true if upper case character
tolower() - converts character to lower case
toupper() - converts character to upper case
So, for example, you could replace the test/modify with:
if ( islower( str[i] ) )
{
str[i] = toupper( str[i] );
}
Pedantically, islower() and toupper() return an unsigned int but that's a separate matter...
You can remove letters from a string if you keep two indices, one for reading and one for writing. The following loop will remove all digits from a string:
int j = 0; // writing index, j <= i
int i; // reading index
for (i = 0; str[i]; i++) {
int c = (unsigned char) str[i];
if (!isdigit(c)) str[j++] = c;
}
str[j] = '\0';
(I've used to character classification functions from <ctype.h> mentioned in Andrew' answer.)
This is safe, because j will always be smaller or equal to i. Don't forget to mark the end of the filtered string with the nullterminator, '\0'. You can combine this filtering with your already existing code for replacing characters.
In your code, you capitalize letters only if they are directly behind a full stop. That's usually not the case, there's a space between full stop and the next word. It's better to establish a context:
shift: capitalize the next letter (beginning or after full stop.)
lock: capitalize all letters (inside quotation marks.)
When you read a letter, decide whether to capitalize it or not depending of these two states.
Putting the filtering and the "shift context§ together:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char str[] = "one. two. THREE. 4, 5, 6. \"seven\", eight!";
int shift = 1; // Capitalize next letter
int lock = 0; // Capitalize all letters
int j = 0; // writing index, j <= i
int i; // reading index
for (i = 0; str[i]; i++) {
int c = (unsigned char) str[i];
if (isdigit(c)) continue;
if (isalpha(c)) {
if (shift || lock) {
str[j++] = toupper(c);
shift = 0;
} else {
str[j++] = tolower(c);
}
} else {
if (c == '"') lock = !lock;
if (c == '.') shift = 1;
str[j++] = c;
}
}
str[j] = '\0';
puts(str);
printf("(length: %d)\n", j);
return 0;
}
In order to remove some characters, you should use 2 index variables: one for reading and one for writing back to the same array.
If you are allowed to use <ctype.h>, it is a much more portable and efficient way to test character types.
Also do not use scanf() with protection against buffer overflow. It is as bad as using gets(). Given the difficulty in specifying the maximum number of bytes to store into str, you should use fgets() instead of scanf().
Here is a modified version:
#include <ctype.h>
#include <stdio.h>
#define MAX 100
int main() {
char str[MAX];
int i, j;
unsigned char last, inquote;
//input string
printf("Enter a string: ");
if (!fgets(str, sizeof str, stdin)) { //read string with spaces
// empty file
return 1;
}
last = '.'; // force conversion of first character
inquote = 0;
//capitalize first character of words
for (i = j = 0; str[i] != '\0'; i++) {
unsigned char c = str[i];
//discard digits
if (isdigit(c)) {
continue;
}
//handle double quotes:
if (c == '"') {
inquote ^= 1;
}
//upper case letters after . and inside double quotes
if (last == '.' || inquote) {
str[j++] = toupper(c);
} else {
str[j++] = tolower(c);
}
if (!isspace(c) && c != '"') {
// ignore spaces and quotes for the dot rule
last = c;
}
}
str[j] = '\0'; // set the null terminator in case characters were removed
printf("Capitalized string is: %s", str);
return 0;
}
I have built a function with the goal of taking text that is fed from elsewhere in the program and removing all whitespace and punctuation from it. I'm able to remove whitespace and punctuation, but the changes don't stay after they are made. For instance, I put the character array/string into a for-loop to remove whitespace and verify that the whitespace is removed by printing the current string to the screen. When I send the string through a loop to remove punctuation, though, it acts as though I did not remove whitespace from earlier. This is an example of what I'm talking about:
Example of output to screen
The function that I'm using is here.
//eliminates all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
int length = strlen(plainText);
//turn capital letters into lower case letters
for (int i = 0; i < length; i++)
plainText[i] = tolower(plainText[i]);
//remove whitespace
for (int i = 0; i < length; i++) {
if (plainText[i] == ' ')
plainText[i] = plainText[i++];
printf("%c", plainText[i]);
}
printf("\n\n");
//remove punctuation from text
for (int i = 0; i < length; i++) {
if (ispunct(plainText[i]))
plainText[i] = plainText[i++];
printf("%c", plainText[i]);
}
}
Any help as to why the text is unchanged after if exits the loop would be appreciated.
Those for loops are not necessary. Your function can be modified as follows and I commented where I made those changes:
char* formatPlainText(char *plainText)
{
char *dest = plainText; //dest to hold the modified version of plainText
while ( *plainText ) // as far as *plainText is not '\0'
{
int k = tolower(*plainText);
if( !ispunct(k) && k != ' ') // check each char for ' ' and any punctuation mark
*dest++ = tolower(*plainText); // place the lower case of *plainText to *dest and increment dest
plainText++;
}
*dest = '\0'; // This is important because in the while loop we escape it
return dest;
}
From main:
int main( void ){
char str[] = "Practice ????? &&!!! makes ??progress!!!!!";
char * res = formatPlainText(str);
printf("%s \n", str);
}
The code does convert the string to lower case, but the space and punctuation removal phases are broken: plainText[i] = plainText[i++]; has undefined behavior because you use i and modify it elsewhere in the same expression.
Furthermore, you do not return plainText from the function. Depending on how you use the function, this leads to undefined behavior if you store the return value to a pointer and later dereference it.
You can fix the problems by using 2 different index variables for reading and writing to the string when removing characters.
Note too that you should not use a length variable as the string length changes in the second and third phase. Texting for the null terminator is simpler.
Also note that tolower() and ispunct() and other functions from <ctype.h> are only defined for argument values in the range 0..UCHAR_MAX and the special negative value EOF. char arguments must be cast as (unsigned char) to avoid undefined behavior on negative char values on platforms where char is signed by default.
Here is a modified version:
#include <ctype.h>
//eliminate all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
size_t i, j;
//turn capital letters into lower case letters
for (i = 0; plainText[i] != '\0'; i++) {
plainText[i] = tolower((unsigned char)plainText[i]);
}
printf("lowercase: %s\n", plainText);
//remove whitespace
for (i = j = 0; plainText[i] != '\0'; i++) {
if (plainText[i] != ' ')
plainText[j++] = plainText[i];
}
plainText[j] = '\0';
printf("no white space: %s\n", plainText);
//remove punctuation from text
for (i = j = 0; plainText[i] != '\0'; i++) {
if (!ispunct((unsigned char)plainText[i]))
plainText[j++] = plainText[i];
}
plainText[j] = '\0';
printf("no punctuation: %s\n", plainText);
return plainText;
}
I am trying to pass a C string (char*) to a function lower(char *) (as in the prototype) that returns a C string char *lower() to main(). But I am not getting the desired output. Point out my mistakes and suggest some techniques for getting the result.
(Note : <string.h> functions are not allowed & the task must be done with pointers). Here is my code,
#include <stdio.h>
#include <stdlib.h>
char *lower(char *);
void main() {
char pass[10], *pass1;
printf("Enter a password\n");
scanf("%s", pass);
pass1 = lower(pass);
printf("Lower case ");
int i = 0;
while (*pass1 != '\0') {
printf("%c", *(pass1 + i));
i++;
}
}
char *lower(char *p) {
while (*p != '\0') {
if (*p >= 'A' && *p <= 'Z') {
*p = *p + 32;
}
p++;
}
return p;
}
There are multiple problems in your code:
main should have the prototype int main(void) a for good style have a return 0; statement at the end of the body.
scanf() should protect the destination array from overflow by specifying the maximum number of characters to read into it: scanf("%9s", pass); and you should check its return value for successful conversion.
you should use pass1[i] instead of *(pass1 + i). Both expressions are equivalent but the first is more readable. Incidentally, another equivalent but surprising alternative is i[pass1], don't use it unless you want to confuse the reader, which might be advisable in a password handling routine.
printing individual characters with printf("%c", pass1[i]) does not seem mandated by the rules posted: use a single printf statement.
Furthermore, the loop test is constant: while (*pass1 != '\0') as you only increment i in the loop. Hence an infinite loop and undefined behavior when you access elements of pass beyond its end.
as you pass the return value to printf(), function lower() should return the original pointer, not the pointer to the end of the argument string.
you should not hard-code the difference between lowercase and uppercase characters, 32 only works for ASCII, not EBCDIC. *p += 'a' - 'A'; would be both more portable and more readable. It works for both ASCII and EBCDIC, but might not for other less common character sets and the test if (*p >= 'A' && *p <= 'Z') is not precise enough for EBCDIC as the uppercase letters do not form a contiguous set. Use the macros from <ctype.h> for a portable solution.
Here is a corrected version:
#include <stdio.h>
#include <ctype.h>
char *lower(char *);
int main(void) {
char pass[80];
printf("Enter a password\n");
if (scanf("%79s", pass) == 1) {
printf("Lower case: %s\n", lower(pass));
}
return 0;
}
char *lower(char *s) {
for (char *p = s; *p != '\0'; p++) {
*p = tolower((unsigned char)*p);
}
return s;
}
If you cannot use <ctype.h>, use this less portable version:
char *lower(char *s) {
for (char *p = s; *p != '\0'; p++) {
if (*p >= 'A' && *p <= 'Z')
*p += 'a' - 'A';
}
return s;
}
char *lower(char *p){
char *ptr = p;
while(*p != '\0'){
if( *p>='A' && *p<='Z' ){
*p = *p + 32;
}
p++;
}
return ptr;
}
why sometimes is good to return something like converted char pointer - to use it in other operations - for example as a parameter in another function call.
I'm trying to create a function that will identify whether the first letter input is upper or lower case then output the rest of the string in that same case(upper/lower).
For example, "Hi there" would become "HI THERE".
I'm not familiar with fgets. Once I run it I can input and press enter and the program doesn't run. I'm not getting any compiler errors. I believe I went wrong in the void shift function.
Also, I know gets is not recommended, is fgets similar? Or is it better to use scanf?
#include <stdio.h>
#include <ctype.h>
void shift (char *my_string); // Function declaration
int main()
{
char inputstring[50];
printf("Enter a string\n");
char *my_string = inputstring;
shift(my_string); // Function
}
void shift (char *my_string) // Function definition
{
int i =0;
char ch;
for(i=0; i<50; i++)
fgets(my_string, 50, stdin);
while(my_string[i])
{
if(ch>='A' && ch<= 'Z') // When first char is uppercase
{
putchar (toupper(my_string[i]));
i++;
}
else if (ch>='a' && ch <= 'z') // When first char is lowercase
{
putchar(tolower(my_string[i]));
i++
}
}
return;
}
You don't need to call fgets() fifty times. It reads a line from stdin and writes it to my_string. It seems you only want to read one line, not fifty (and keep only the last one). The 50 is the maximum number of characters (minus one) that will be read and written to the buffer. This limit is to prevent buffer overflow. See fgets().
Try removing the for loop on the line before the fgets() call. Also, you don't need the my_string in main(). The corrected code:
#include <stdio.h>
#include <ctype.h>
void shift (char *my_string);//function declaration
int main()
{
char inputstring[50];
printf("Enter a string\n");
shift(inputstring);
}
void shift (char *my_string) //function definition
{
int i;
char ch;
if ( fgets(my_string, 50, stdin) == NULL )
return;
ch = my_string[0];
for ( i=0; my_string[i]; i++ )
{
if(ch>='A' && ch<= 'Z') //when first char is uppercase
{
putchar (toupper(my_string[i]));
}
else if (ch>='a' && ch <= 'z')//when first char is lowercase
{
putchar(tolower(my_string[i]));
}
}
return;
}
Edit: Added ch initialization, pointed out by #thurizas. Changed while loop to for loop. Added check to return value of fgets() as suggested by #JonathanLeffler. (See his comment about the buffer size.)
Here is another solution for your problem,
#include <stdio.h>
#include <ctype.h>
void convertTo (char *string);
int main()
{
char inputString[50];
printf("Enter a string\n");
convertTo(inputString);
}
void convertTo (char *string)
{
int i;
char ch;
gets(string);
ch = string[0];
for ( i=0; string[i]; i++ )
{
if(ch>='A' && ch<= 'Z')
{
if(string[i]>='a' && string[i]<= 'z')
string[i] = string[i] - 32;
}
else if (ch>='a' && ch <= 'z')
{
if(string[i]>='A' && string[i]<= 'Z')
string[i] = string[i] + 32;
}
}
printf("%s\n", string);
return;
}
All ASCII characters are represented by 7-bits. (thus the term 7-bit ASCII) The only bitwise difference between lower-case and upper-case is that bit-5 (the sixth bit) is set for lowercase and cleared (unset) for uppercase. This allows a simple bitwise conversion between lowercase and uppercase (either by adding/subtracting 32 or by simply flipping bit-5 directly.)
+-- lowercase bit
|
a = 01100001 A = 01000001
b = 01100010 B = 01000010
c = 01100011 C = 01000011
...
This allows a simple test and conversion if the first character is upper-case:
#include <stdio.h>
enum { MAXC = 50 };
char *shift (char *my_string);
int main (void)
{
char inputstring[MAXC] = {0};;
printf ("\n Enter a string: ");
if (shift (inputstring))
printf (" my_string is : %s\n", inputstring);
return 0;
}
char *shift (char *my_string)
{
char *p;
if (!(p = fgets (my_string, MAXC, stdin))) return NULL;
if (*p == '\n') return NULL; /* Enter only pressed */
if ('A' <= *p && *p <= 'Z') /* test for upper case */
for (; *p; p++) /* convert lower/upper */
if ('a' <= *p && *p <= 'z') *p &= ~(1 << 5);
return my_string;
}
Example Use
$ ./bin/case_1st_to_upper
Enter a string: this is my string
my_string is : this is my string
$ ./bin/case_1st_to_upper
Enter a string: This is my string
my_string is : THIS IS MY STRING
Using only stdio.h, string.h and stdlib.h libraries how would I go about implementing this?
I'm quite new to programming so please bear with me!
Allocate a new char array of the same length as your string. Convince yourself that this is enough space. Don't forget the NUL.
Loop through the string, copying to the new string only those characters that are alphanumeric. You can't do this portably without also including <ctype.h> and using a function/macro from that header, unless you're going to enumerate all characters that you consider alphanumeric.
Again, don't forget the NUL.
Since this is homework, here is the verbal description:
Run a loop over the original string and use the functions isalnum() to determine if a character is alphanumeric. Maintain a second char array of reasonable size and every time you encounter an AlphaNum, insert it to that array. Once all AlphaNum characters have been copied to the second array, NULL terminate it and you have your string.
Note: isalnum() is defined in ctype.h, so if you aren't allowed to use that, you may have to define this function for yourself. That is another exercise of it's own.
Every char you read in your string is a byte (you can think it as a number between 0 and 255, and that's how the computers handle them) so you just need to check the ascii table to see what letter refers to.
Every alphanumerical char is in this range: [48, 58] (for numbers), or [65, 90] (upper case), or [97, 122] (lower case).
Look at this:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 64
int isalphanum(char); /*states if a char is alphanumerical or not*/
char *getalphanum(char *, char*); /*modifies the second string to get the result*/
int main(void) {
char in[SIZE] = "Hello, W##########orl...,.,d!"; /*just a random to try out*/
char out[SIZE];
getalphanum(in, out);
printf("%s", out);
return 0;
}
int isalphanum(char a) {
if ((a >= 48) && (a <= 58))
return 1;
if ((a >= 65) && (a <= 90))
return 1;
if ((a >= 97) && (a <= 122))
return 1;
return 0;
}
char *getalphanum(char *s, char *t) {
if ((s == NULL) || (t == NULL)) /*tests if the strings are "handble"*/
return NULL;
int i = 0;
int j = 0;
char c;
while ((c = *(s + i)) != '\0') {
if (isalphanum(c)){
*(t + j) = c;
j++;
}
i++;
}
*(t + j) = '\0';
return t;
}
This code works and is very simple and can be improved, but there is evertything you need.
The best way is to use the isalnum() from ctype.h but now that is not an option, I have written a not-standard/non-portable function called isalnum_not_prefered() which is the equivalent of ctype.h's isalnum().
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int isalnum_not_prefered(char s)
{
if((s >= 'A' && s <= 'Z') ||
(s >= 'a' && s <= 'z') ||
(s >= '0' && s <= '9'))
return 1;
return 0;
}
int main(void)
{
char str[] = "this!234$#&##$^is5##$a##$4677~=_?}valid2234kjstring";
int len = strlen(str);
int i, j=0;
char *newstr1 = NULL;
char *newstr2 = NULL;
if ((newstr1 = (char *) malloc(sizeof(char) * len + 1)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
for (i=0 ; i<len ; i++) {
if (isalnum(str[i])) {
newstr1[j] = str[i];
j++;
}
}
newstr1[j] = '\0';
if ((newstr2 = (char *) malloc(sizeof(char) * len + 1)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
j=0;
for (i=0 ; i<len ; i++) {
if (isalnum_not_prefered(str[i])) {
newstr2[j] = str[i];
j++;
}
}
newstr2[j] = '\0';
printf("string : %s \n", str);
printf("result1 : %s \n", newstr1);
printf("result2 : %s \n", newstr2);
free(newstr1);
free(newstr2);
return 0;
}
Points to note:
strings in C is terminated with \0. So the new string that your are populating should also terminate with \0
malloc()'ed memory must be free()'ed
malloc() errors should be handled
this code is not portable as it assumes the machines character set to be ASCII. If the hardware supports some other character set (say EBCDIC) then this may not work as expected.
Hope this helps!