i'm practicing strings now and what i try to do in this program is print something like: hello world into HellO WorlD as an output.
My code is the following one:
#include <stdio.h>
#include <string.h>
void convertir(char cadena[200]){
int length = strlen(cadena);
int i;
printf("%c", cadena[0]-32); // Prints letter in caps
for(i=1;i<length-1;i++){
if(cadena[i] == ' '){ // Search if there is space
printf("%c", cadena[i-1]-32);
i=i+1; // Adds vaule on i with accumulator to make caps the letter after the space
printf(" %c", cadena[i]-32); // prints letter in caps after space
} else {
printf("%c", cadena[i]); // prints everything in the string
}
}
printf("%c", cadena[length-1]-32);
}
int main(int argc, char const *argv[]) {
char cadena[200];
printf("Introduce un texto: ");
gets(cadena);
convertir(cadena);
return 0;
}
What the code compiled returns me after typing hello world is: HelloO WorlD, i'm trying to replace that o in HelloO but i'm getting confused...
Any help is appreciated.
Thank you.
I made the following changes to your for loop and it appears to work as you expect it to:
for(i=1;i<length-1;i++)
{
if(cadena[i + 1] == ' ') /*** Look If Next Character Is A Space ***/
{
printf("%c", cadena[i]-32); /*** Print Current Character In Uppercase ***/
i=i+1; // Adds vaule on i with accumulator to make caps the letter after the space
printf(" %c", cadena[i + 1]-32); /*** Print Character After Space In Caps ***/
i=i+1; // Adds vaule on i with accumulator to make caps the letter after the space
}
else
{
printf("%c", cadena[i]); // prints everything in the string
}
}
Output:
$ ./main.exe
Introduce un texto: hello world
HellO WorlD
Moving forward, there are several things you should do to make your program more robust:
Don't assume there aren't leading spaces (or whitespace)
Don't assume each character is lowercase
Don't assume each character is a letter
Don't assume there is only one space (or whitespace) between words
Any help is appreciated.
Use isalpha() to detect if a char is part of a word.
Use toupper() to convert to an uppercase character.
Use unsigned char for isalpha(), toupper() to avoid UB with negative char values.
Employ a boolean to keep track if a beginning of a word is possible.
#include <ctpye.h>
#include <stdbool.h>
void convertir(const char *cadena) {
const unsigned char *s = (const unsigned char *) cadena;
bool potential_start_of_word = true;
while (*s) {
// If next character is not an alpha or we area at the start of a word ...
if (!isapha(s[1]) || potential_start_of_word) {
printf("%c", toupper(*s));
} else {
printf("%c", *s);
}
potential_start_of_word = !isapha(*s);
s++;
}
}
No need for strlen(cadena)
You can use ctype.h's toupper() function or provide your own implementation. Something like this:
int toupper(int c) {
return (c-32);
}
And then use it like this:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void convertir(char cadena[200]){
int length = strlen(cadena);
int i;
cadena[0] = toupper(cadena[0]);
cadena[length-1] = toupper(cadena[length-1]);
for(i=0; i<length; i++){
if(cadena[i] == ' '){ // Search if there is space
cadena[i-1] = toupper(cadena[i-1]);
if (i+1 < length) cadena[i+1] = toupper(cadena[i+1]);
}
}
printf("%s\n", cadena);
}
int main(int argc, char *argv[]) {
char cadena[200];
printf("Introduce un texto: ");
gets(cadena);
convertir(cadena);
return 0;
}
Related
My code should delete all vowels from the string that i give. But it does not delete if the vowel is the last character of the string.
#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
char str[100];
printf("Enter a string :\n");
gets(str);
int len=strlen(str);
while(str[i]!='\0')
{
printf("%c",str[i]);
if(str[i]=='A'||str[i]=='a'||str[i]=='E'||str[i]=='e'||str[i]=='I'||str[i]=='i'||str[i]=='O'||str[i]=='o'||str[i]=='U'||str[i]=='u')
printf("\b");
i++;
}
return 0;
}
Like if i provide the string Hello it prints Hllo where it should print Hll ...But if i change the while condition to (i
I guess printing \b doesn’t do what you think it does. It does not delete the last printed character, it just prints an additional ‘backspace’ character, which on some output devices (such as console) moves backwards by one character. (Then, the next character overwrites the one you wanted ‘deleted’.)
Don’t do that. Instead, move the ‘if’ statement so that you don’t print those vowels in the first place!
You can try this
#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
char str[100];
printf("Enter a string :\n");
fgets(str,100, stdin);
int len=strlen(str);
while(str[i]!='\0')
{
if(str[i]=='A'||str[i]=='a'||str[i]=='E'||str[i]=='e'||str[i]=='I'||str[i]=='i'||str[i]=='O'||str[i]=='o'||str[i]=='U'||str[i]=='u'){
continue;
}else{
printf("%c",str[i]);
}
i++;
}
return 0;
}
This is for a homework assignment, so it can not use loops of any kind as a way to force recursion practice. I am also not to change the method signature, or anything in the main() function.
The function is intended to use recursion to print a string in reverse. I learned on this site (Strip first and last character from C string) how to remove the last character in a string. When I try and reproduce it in my code, the program crashes on execution. Here is that code:
#include <stdio.h>
#include <string.h>
void print_reverse_str(char *str) {
if (strlen(str) == 1)
printf("%c", &str[0]);
else {
int len = strlen(str);
int lastIndex = len - 1;
char endChar = str[lastIndex];
printf("%c", &endChar);
str[lastIndex] = 0;
print_reverse_str(str);
}
}
int main() {
print_reverse_str("My string");
printf("\n");
print_reverse_str("!ti tog uoy ,siht daer nac uoy fI");
printf("\n");
}
You can not change a string literal.
Character display with printf. E.g printf("%c", character);, not &character
try this.
#include <stdio.h>
#include <string.h>
void print_reverse_str(char *str){
if (*str){
print_reverse_str(str+1);
printf("%c", *str);
}
}
int main(){
print_reverse_str("My string");
printf("\n");
print_reverse_str("!ti tog uoy ,siht daer nac uoy fI");
printf("\n");
}
I have a relatively simple problem. A user is supposed to run the program,type in a message of 30 characters or less and then the case of the individual letters of the messages will be toggled.(lowercase letters will be made upercase and vice versa). Everything is fine except for the part of changing the case. I am supposed to use a pointer to a char in an array and pass it as a function argument to toggle_case. Please assist me on how to achieve this.
Here is the code.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void read_message(char *message, int *message_size);
void toggle_case(char *character);
void count_cv(char* message);
int main() {
char message[30];
int message_size;
char *message_pointer;
message_pointer = message;
read_message(message, &message_size);
int i = 0;
for(i =0; i<30; i++){
toggle_case(&message_pointer[i]);
}
printf("New string: %s",message);
return 0;
}
void read_message(char *message, int *message_size){
printf("Enter your string (maximum 30 characters): ");
fgets(message, 30, stdin);
}
void toggle_case(char *character){
//check if character is a letter
if (isalpha(*character)) {
//Check if the character is upper case
if(isupper(*character)){
//convert the character to lower case
tolower(*character);
} else {
//Check if the character is lower case
//convert the character to upper case
toupper(*character);
}
}
}
void count_cv(char* message){
}
tolower and toupper return the new character, you need to assign it back to the location you're updating.
if (isupper(*character)) {
*character = tolower(*character);
} else {
*character = toupper(*character);
}
BTW, you don't need to check if the character is a letter first. tolower and toupper will simply return the character unchanged if it's not a letter.
I'm new to this forum and would like to seek help. I'm trying to modify an anagram program based on code from http://www.sanfoundry.com/c-program-...ings-anagrams/.
This time, however, I have used array pointers to obtain input from the user. I have also created a function "check_input" to ensure that the input consists of ONLY characters and excludes symbols(!, #, $). However, when I ran the program, it still accepts those symbols and does not break like I wanted it to. Please help.
Plus, I intend to make the program treat upper-case letters the same way as lower-case letters. Can this be achieved by using the "stricmp" function? If so, where should I place that function? Alternative methods are also appreciated.
Update: Sorry. I've added the check_input code at the bottom.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int test_anagram(char *ptrArray1, char *ptrArray2);
int check_input(char array1[], char array2[]);
int main()
{
char array1[100], array2[100];
char *pArray1, *pArray2;
int flag;
pArray1 = array1;
pArray2 = array2;
printf("Enter the first word: \n");
gets(pArray1);
printf("Enter the second word: \n");
gets(pArray2);
check_input(pArray1, pArray2);
flag = test_anagram(pArray1, pArray2);
if(flag == 1){
printf("\"%s\" and \"%s\" are anagrams.\n", pArray1, pArray2);
}else{
printf("\"%s\" and \"%s\" are not anagrams.\n", pArray1, pArray2);
}
return 0;
}
int test_anagram(char array1[], char array2[])
{
int num1[26] = {0}, num2[26] = {0}, i = 0;
while(array1[i] != '\0')
{
num1[array1[i] - 'a']++;
i++;
}
i = 0;
while(array2[i] != '\0')
{
num2[array2[i] - 'a']++;
i++;
}
for(i=0;i<26;i++)
{
if(num1[i] != num2[i]){
return 0;
}
return 1;
}
}
int check_input(char array1[], char array2[])
{
while(isalpha((int)array1) != 1){
break;
}
while(isalpha((int)array2) != 1){
break;
}
}
You haven't (yet) posted the full code of the check_input() function but one advice would be to validate the input when the user inputs every character.
You can do this using f.e. the getchar() function and checking if the inputted character is a letter, as well as converting it to the lowercase (or uppercase if you will).
You can do lowercase convertion like this:
#include <ctype.h>
// ...
tolower('A');
what i want to do is take a big input(read till users press enter(\n) ) and then call a function that puts the first word of this input(read till ' '). My problem is that even though it looks pretty simple it also has 2 extra allien characters in it. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void findChoise(char *input, char *choise);
int main()
{
char choise[12];
char input[300];
printf("give me the input: ");
gets(input);
printf("%s\n", input);
printf("%s%d\n", "length of input: ", strlen(input));//for checking
findChoise(input, choise);
printf("%s%d\n", "length of output: ", strlen(choise));//for checking
printf("%s\n", choise);
return 0;
}
void findChoise(char *input, char *choise)
{
int i=0;
while(input[i] != ' ')
{
choise[i] = input[i];
i++;
};
}
What you have already done is very close. You are just missing the null character at the end of the string ("\0"). I have cleaned up your code a little bit and fixed somethings. Please read through it and try and understand what is going on.
Main things to note:
All strings are arrays of characters and terminates with a null character "\0"
When you declare buffers(input and choice), try to make them a power of 2. This has to due with how they are stored in memory
Avoid using gets and try scanf instead
#include <cstdio>
void findChoice(char*, char*);
int main() {
char choice[16];
char input[512];
scanf("%s", input);
findChoice(choice, input);
printf("%s", choice);
return 0;
}
void findChoice(char* input, char* choice) {
int i = 0;
while(input[i] != ' ') {
choice[i] = input[i];
++i;
}
choice[i] = '\0';
}
You also need to write a null character to end the choise string:
void findChoise(char *input, char *choise)
{
int i=0;
while(input[i] != ' ')
{
choise[i] = input[i];
i++;
}
choise[i] = 0;
}
also don't use gets:
fgets(input, sizeof(input), stdin);
and use %zu to print size_t:
printf("%s%zu\n", "length of input: ", strlen(input));