C function to capitalize the first character of a pointer string - c

I want to capitalize the first character of a pointer string.
For example, input: john
Output: John
I can do it with arrays (s[0] = toUpper(s[0]), but is there a way to do it with pointers?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 30
int transform(char *s)
{
while (*s != '\0')
{
*s = toupper(*s);
s++;
}
return *s;
}
int main()
{
printf("String: ");
char *s[MAX];
getline(&s,MAX);
transform(s);
printf("Transformed char: %s", &s);
}
int getline(char *s, int lim)
{
int c;
char *t=s;
while (--lim>0 && (c=getchar())!=EOF && c!='\n') *s++=c;
*s='\0';
while (c!=EOF && c!='\n')
c=getchar();
return s-t;
}
This code turns the whole string to upper case.

Your transform function is looping through the entire string and running toupper on each one. Just run it on the first character:
void transform(char *s)
{
*s = toupper(*s);
}
Also, you declare s in main as an array of pointers to char. You just want an array of char:
int main()
{
printf("String: ");
char s[MAX];
getline(s,MAX); // don't take the address of s here
transform(s);
printf("Transformed char: %s", s); // or here
}
You want to move main to the end of the file as well, so that getline is defined before it is called.

Easy solution:
void transform(char* p) {
//Only first character
*p = toupper(*p);
}
//Call like that:
char str[] = "test";
transform(str); //str becomes: "Test"

Related

Deleting a char and moving it in a string

I need ideas for a recursive code that deletes a specific char in a string, and move all the other sting chars together
for Example :
"the weather is cloudy"
the entered char is 'e':
result :
"th wathr is cloudy"
I really don't have any idea how to start, thanks for the help.
#include <stdio.h>
void remove_impl(char* s, char c, char* d) {
if (*s != c) {
*d++ = *s;
}
if (*s != '\0') {
remove_impl(++s, c, d);
}
}
void remove(char* s, char c) {
remove_impl(s, c, s);
}
int main() {
char s[] = "the weather is cloudy";
remove(s, 'e');
puts(s);
}
How it works? Consider remove_impl. s is the original string, c is the character to be deleted from s, d is the resulting string, into which the characters of s, not equal to c, are written. Recursively iterates through the characters of s. If the next character is not equal to c, then it is written in d. The recursion stop point is the condition of checking that the end of s is reached. Since it is necessary to modify the source string, the wrapper is implemented (remove) in which as d, the original string (s) is passed.
An easy way to do it is to loop over the string and add any letter that doesn't match the unwanted letter.
Here's a demonstration:
char *source = "the weather is cloudy";
int source_len = strlen(source);
char *target = (char *)calloc(source_len, sizeof(char));
int target_len = 0;
char to_remove = 'e';
for(int i = 0; i < source_len; i++)
{
if(source[i] != to_remove)
{
target[target_len++] = source[i];
}
}
puts(target); // Output "th wathr is cloudy" in the console
My turn to make a proposal ! I add a assert test and use existing functions (strchr and strcpy).
#include <string.h>
#include <stdio.h>
#include <assert.h>
int removeChar(char *str, char chr)
{
assert(str != 0); // Always control entry !
char *str_pnt = strchr(str, chr);
if (str_pnt) {
strcpy(str_pnt, str_pnt+1);
removeChar(str_pnt, chr);
}
}
void main (void)
{
char str[] = "the weather is cloudy";
char char_to_delete = 'e';
removeChar(str, char_to_delete);
puts(str);
}
This can be done in many ways. What i am thinking right now is store not Allowed char array which going to filter which char should show or not. Something like following..
#include <stdio.h>
#include <string.h>
// Global Scope variable declaration
int notAllowedChar[128] = {0}; // 0 for allowed , 1 for not allowed
char inputString[100];
void recursion(int pos, int len) {
if( pos >= len ) {
printf("\n"); // new line
return;
}
if( notAllowedChar[inputString[pos]]) {// not printing
recursion( pos + 1 , len );
}
else {
printf("%c", inputString[pos]);
recursion( pos + 1 , len );
}
}
int main() {
gets(inputString); // taking input String
printf("Enter not allowed chars:: "); // here we can even run a loop for all of them
char notAllowed;
scanf("%c", &notAllowed);
notAllowedChar[notAllowed] = 1;
int len = strlen(inputString);
recursion( 0 , len );
}
How this work
Lets say we have a simple string "Hello world"
and we want l should be removed from final string, so final output will be "Heo word"
Here "Hello world" length is 11 chars
before calling recursion function we make sure 'l' index which is 108 ascii values link 1 in notAllowedChar array.
now we are calling recursion method with ( 0 , 11 ) value , In recursion method we are having mainly 2 logical if operation, first one is for base case where we will terminate our recursion call when pos is equal or more than 11. and if its not true , we will do the second logical operation if current char is printable or not. This is simply just checking where this char is in notAllowedChar list or not. Every time we increase pos value + 1 and doing a recursion call, and finally when pos is equal or more than 11 , which means we have taken all our decision about printing char or not our recursion will terminate. I tried assign variable with meaningful name. If you still not understand how this work you should go with simple recursion simulation basic ( search in youtube ) and also you should try to manually debug how value is changing in recursion local scope. This may take time but it will be worthy to understand. All the very best.
#include <stdio.h>
/**
* Returns the number of removed chars.
* Base case: if the current char is the null char (end of the string)
* If the char should be deleted return 1 + no of chars removed in the remaining string.
* If it's a some other char simply return the number of chars removed in the remaining string
*/
int removeCAfterwardsAndCount(char* s,char c){
if((*s) == '\0'){
return 0;
}
if((*s) == c){
int noOfChars = removeCAfterwardsAndCount(s+1,c);// s+1 means the remaining string
s[noOfChars] = *s; // move the current char (*s) noOfChars locations ahead
return noOfChars +1; // means this char is removed... some other char should be copied here...
}
else{
int noOfChars = removeCAfterwardsAndCount(s+1,c);
s[noOfChars ] = *s;
return noOfChars ; // means this char is intact ...
}
}
int main()
{
char s[] = "Arifullah Jan";
printf("\n%s",s);
int totalRemoved = removeCAfterwardsAndCount(s,'a');
char *newS = &s[totalRemoved]; // the start of the string should now be originalPointer + total Number of chars removed
printf("\n%s",newS);
return 0;
}
Test Code Here
To avoid moving the chars using loops. I am just moving the chars forward which creates empty space in the start of the string. newS pointer is just a new pointer of the same string to eliminate the empty/garbage string.
#include <stdio.h>
void RemoveChar(char* str, char chr) {
char *str_old = str;
char *str_new = str;
while (*str_old)
{
*str_new = *str_old++;
str_new += (*str_new != chr);
}
*str_new = '\0'; }
int main() {
char string[] = "the weather is cloudy";
RemoveChar(string, 'e');
printf("'%s'\n", string);
return 0; }
#include <stdio.h>
#include <string.h>
char *remove_char(char *str, int c)
{
char *pos;
char *wrk = str;
while((pos = strchr(wrk, c)))
{
strcpy(pos, pos + 1);
wrk = pos;
}
return str;
}
int main()
{
char str[] = "Hello World";
printf(remove_char(str, 'l'));
return 0;
}
Or faster but mode difficult to understand version:
char *remove_char(char *str, int c)
{
char *pos = str;
char *wrk = str;
while(*wrk)
{
if(*wrk == c)
{
*wrk++;
continue;
}
*pos++ = *wrk++;
}
*pos = 0;
return str;
}
Both require the string to be writable (so you cant pass the pointer to the string literal for example)

Reading input char by char using realloc in C

I would like to read input char by char and save it as a word into char* array. I don't know how long the input will be, so i want to alloc the memmory dynamicaly. The program ends,when the char is whitespace. How can i do this using realloc?
There is my code:
#include <stdio.h>
int main(void) {
char *word=malloc(1*sizeof(char));
char c;
int numOfChars=0;
c=getchar();
word[0]=c;
numOfChars++;
while((c=getchar())!=' '){
numOfChars++;
realloc(word,numOfChars);
word[numofChars-1]=c;
}
printf("%s", word);
return 0;
}
Example input:Word
Example output:Word
The program can look the following way. Take into account that the input is buffered and filled until a new line character is entered that is also a white space character. And the result word must be zero terminated if you are going to use format specifier %s to output it.
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int c;
size_t n;
char *word;
char *tmp;
n = 0;
word = malloc( n + 1 );
word[n++] = '\0';
printf( "Enter a word: " );
while ( ( c = getchar() ) != EOF && !isspace( c ) && ( tmp = realloc( word, n + 1 ) ) != NULL )
{
word = tmp;
word[n-1] = c;
word[n++] = '\0';
}
printf( "You've entered \"%s\"\n", word );
free( word );
}
The program output might look like
Enter a word: Hello
You've entered "Hello"
In order to explain what I had in mind, i quickly set up this little programm to explain how to use an exponential growth :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INITIAL_CAPACITY 100
#define GROW_FACTOR 1.5
struct string_buffer {
size_t capacity;
size_t length;
char *buffer;
};
typedef struct string_buffer string_buffer_t;
string_buffer_t *sb_init(void);
static void sb_grow(string_buffer_t *sb);
void sb_shrink(string_buffer_t *sb);
char *sb_release(string_buffer_t *sb);
void sb_append_char(string_buffer_t *sb, char c);
char *sb_peek_string(string_buffer_t *sb);
int main(void)
{
string_buffer_t *sb=sb_init();
int c;
while ( (c=getchar())!=' ' && c!='\n' && c!=EOF )
sb_append_char(sb, c);
char *string=sb_release(sb);
printf("string : \"%s\"\nlength : %zu\n", string, strlen(string));
free(string);
return 0;
}
string_buffer_t *sb_init(void)
{
string_buffer_t *new=malloc(sizeof *new);
if (new==NULL) exit(EXIT_FAILURE);
new->capacity=INITIAL_CAPACITY;
new->length=1;
new->buffer=malloc(INITIAL_CAPACITY);
if (new->buffer==NULL) exit(EXIT_FAILURE);
new->buffer[0]=0;
return new;
}
static void sb_grow(string_buffer_t *sb)
{
char *new=realloc(sb->buffer, (size_t) (GROW_FACTOR*sb->capacity));
if (new==NULL) exit(EXIT_FAILURE);
sb->capacity=(size_t) (GROW_FACTOR*sb->capacity);
sb->buffer=new;
}
void sb_shrink(string_buffer_t *sb)
{
char *new=realloc(sb->buffer, sb->length);
if (new==NULL) exit(EXIT_FAILURE);
sb->buffer=new;
}
char *sb_release(string_buffer_t *sb)
{
sb_shrink(sb);
char *string=sb->buffer;
free(sb);
return string;
}
void sb_append_char(string_buffer_t *sb, char c)
{
if (sb->capacity==sb->length) sb_grow(sb);
sb->buffer[sb->length-1]=c;
sb->buffer[sb->length]=0;
sb->length=sb->length+1;
}
This will do
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *ptr;
char *word=malloc(1*sizeof *word);
char c;
int numofChars=0;
printf("Enter string terminated by a space :");
c=getchar();
word[0]=c;
numofChars++;
while((c=getchar())!=' '){
numofChars++;
ptr=realloc(word,numofChars*sizeof *ptr);
if(ptr!=NULL)
{
word=ptr;
word[numofChars-1]=c;
}
}
/* You need to append a null character to make it a valid string */
numofChars++;
ptr=realloc(word,numofChars*sizeof *ptr);
if(ptr!=NULL)
{
word=ptr;
word[numofChars-1]='\0';
}
printf("Word : %s\n", word);
free(word); // Freeing word/
return 0;
}
Well, you may write a function to replace
numofChars++;
ptr=realloc(word,numofChars*sizeof *ptr);
if(ptr!=NULL)
{
word=ptr;
word[numofChars-1]='\0';
}
Note:
It is not suggested that you do
word=realloc(word,numOfChars*sizeof(char));
because in case realloc fails, you have memory leak. So I used ptr here.

strcat is giving me a segmentation fault error

After verifying that strcat is where the error occurs, I then check the previous example in my assignment. In my previous examples I use strcat(actually strncat) in the same fashion as I do for my following code. I am not too sure.
The purpose of my program is to loop through "string" and remove any occurances the character 'c' from string.
main.c:
char string[100]={0}, c[3];
printf("Enter a String: ");
fgets(string, 100, stdin);
if (string[98] == '\n' && string[99] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }
printf("Enter a Char: ");
fgets(c, 2, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
rmchr(string, c[0]);
header:
rmchr(char *string, char c)
{
int i=0;
char *word[100];
int s = strlen(string);
for(i=0; i<=(s-2); i++)
{
if(string[i] != c)
{
strcat(word, string[i]);
}
}
}
char *word[100];
It will hold a string in your program so use:
char word[100];
that is, an array of char instead of an array of char *.
Then strcat concatenates to a string but word is not initialized. Make it a string with:
word[0] = '\0';
Then string[i] is a character but strcat needs pointers to character arguments: to use a pointer use &string[i].
Finally the problem in your rmchr function is it has to return something, either through the arguments or via a return statement but it doesn't.
There are more than one point to mention here, like
rmchr() definition should have a return type, maybe void if you're not returning anything.
[FWIW, In that case, I wounder, how you'll make use of the local variable word]
inside rmchr(), word needs to be an array of chars, not char pointers. You need to change char * word[100] to char word[100].
In strcat(), both the arguments, needs to be a pointer. You need to use &string[i], in that case.
The following seems to compile fine but your code doesnt do quite what you said you wanted, "The purpose of my program is to loop through "string" and remove any occurances the character 'c' from string.". the function doesn't remove the character or return a copy of the string with the character excluded. I wrote a function that copies the string after removing the character and returns pointer to it. below is your code a bit modified and under it is my function
//Just a compilable version of your code, not sure if it does what u want
#include <stdio.h>
#include <string.h>
void rmchr(char *string, char c)
{
int i=0;
char word[100];
int s = (int)strlen(string);
for(i=0; i<=(s-2); i++)
{
if(string[i] != c)
{
strcat(word, (char *)(&string[i]));
}
}
}
int main(int argc, const char * argv[]) {
char string[100] = {0}, c[3];
char ch;
printf("Enter a String: ");
fgets(string, 100, stdin);
if (string[98] == '\n' && string[99] == '\0') {
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
}
printf("Enter a Char: ");
fgets(c, 2, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
rmchr(string, c[0]);
return 0;
}
There you go, with a demo main
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* rmchr(char *string, char ch)
{
int counter = 0;
int new_size = 0;
char corrected_string[100];
while (string[counter] != '\n' && string[counter] != '\0' && string[counter] != EOF) {
if (string[counter] != ch) {
corrected_string[new_size] = string[counter];
new_size++;
}
counter++;
}
char *new_string = (char *)malloc((new_size+1) * sizeof(char));
for (int j = 0; j <= new_size; j++) {
new_string[j] = corrected_string[j];
}
return new_string;
}
int main(int argc, const char * argv[]) {
char *s = "The char 'c' will be removed";
char *new = rmchr(s, 'c');
printf("%s", new);
return 0;
}

How to put letter out of string? C language

void getAvailableLetters(char lettersGuessed[], char availableLetters[])
is function that I need to create. It must use strings.
availableLetters are letters of alphabet
lettersGuessed are letters inserted by user
function is supposed to do this:
Available letters: abcdefghijklmnopqrstuvwxyz
Gimme a letter: (let's guess 'm')
Available letters: abcdefghijklnopqrstuvwxyz //all without letter m
Gimme a letter: (let's hess 'b')
Available letters: acdefghijklnopqrstuvwxyz //all without letters m & b
Any algorythms, advices, codes or smth what would help me to do it would be great.
Test this one out. The function char_replace() takes in the source string, the character to find and the string to replace the character (can be also one char). In your case, you pass "" (empty value) for the char to be replaced with, because you want to remove it. But the parameter might come in handy, so I included it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *char_replace(char *, char, char *);
int main(void) {
char input[4096] = "abcdefghijklmnopqrstuvwxyz";
char *signature = char_replace(input, 'a', "");
printf("%s\n", input);
return 0;
}
char *char_replace(char *str, char find, char *replace) {
char *ret=str;
char *wk, *s;
// string duplication
wk = s = strdup(str);
while (*s != 0) {
if (*s == find){
while(*replace)
*str++ = *replace++;
++s;
} else
*str++ = *s++;
}
*str = '\0';
free(wk);
// returning the result string
return ret;
}
This approach is counting on the input array of chars (string) to have enough space with 4096 allocated to it.
#include<stdio.h>
#include<string.h>
char availableLetters[27]={"abcdefghijklmnopqrstuvwxyz"},lettersGuessed[2];
void getAvailableLetters(char lettersGuessed[], char availableLetters[])
{
int i,flag=0;
for(i=0;availableLetters[i]!='\0';i++)
{
if(availableLetters[i]==lettersGuessed[0])
{
flag=1;
for(;availableLetters[i]!='\0';i++)
{
availableLetters[i]=availableLetters[i+1];
}
}
if(flag==1)
{
availableLetters[i-1]='\0';
break;
}
}
}
input()
{
printf("Gimme a letter:");
scanf("%c",&lettersGuessed[0]);
fflush(stdin); //deleting extra characters
lettersGuessed[1]='\0';
}
output()
{
printf("Available letters:");
puts(availableLetters);
}
main()
{
output();
input();
getAvailableLetters(lettersGuessed,availableLetters);
output();
input();
getAvailableLetters(lettersGuessed,availableLetters);
output();
}

Whitespace replace in C language

What is the right way to replace a white space with _ in string passCode with 2 characters?
In the end it should input/output: (a ) → (a_). Is there a way to do this using the isspace?
isspace(passCode[2]) == 0;
Check if the character is a space if yes, then replace it with _.
For example:
#include <stdio.h>
#include <ctype.h>
int main ()
{
int i=0;
unsigned char str[]="a ";
while (str[i])
{
if (isspace(str[i]))
str[i]='_';
i++;
}
printf("%s\n",str);
return 0;
}
A simple manner for character substitution is simply to create a pointer to the string and then check each character in the string for value x and replace it with character y as you go. An example would be:
#include <stdio.h>
int main (void)
{
char passcode[] = "a ";
char *ptr = passcode;
while (*ptr)
{
if (*ptr == ' ')
*ptr = '_';
ptr++;
}
printf ("\n passcode: %s\n\n", passcode);
return 0;
}
output:
$ ./bin/chrep
passcode: a_
The best way to do this is:
#include <stdio.h>
void replace_spaces(char *str)
{
while (*str)
{
if (*str == ' ')
*str = '_';
str++;
}
}
int main(int ac, int av)
{
char *pass = 'pas te st';
replace_spaces(pass);
printf("%s\n", pass);
return (0);
}
pass i now equal to 'pas_te_st'.

Resources