I am very confused to create a function which will print a string and ask user to enter two numbers and then function will replace those number of words with one another.
I have added the image below as sample.
enter image description here
This is my homework, I have created other 3 functions, but don't really get this one.
Could somebody please help me how can I convert the words into numbers and then replace those number of words with one another.
This is my program it can break the string into words but how can i replace position of words.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
printf(" Input a string : ");
fgets(str1, sizeof str1, stdin);
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[i];
j++;
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
Seems to me that you are doing pretty good so far (your code can't handle comma but you can add that later). So let's assume that your newString actually contains the individual words.
So your next step is to construct a new string str2 from the individual words you have in newString. While you do that you can simply swap the two words of interest. To build the new string the strcat function could be helpful.
The code below is not fully correct but it may give you some ideas for getting on with your homework:
int lowest_index_to_swap = some_number
int highest_index_to_swap = some_higher_number
char str2[100] = "";
for (i=0; i<number_of_words_found; ++i)
{
if (i == lowest_index_to_swap)
strcat(str2, newString[highest_index_to_swap];
else if (i == highest_index_to_swap)
strcat(str2, newString[lowest_index_to_swap];
else
strcat(str2, newString[i];
strcat(str2, " ";
}
Here is code snippet what I tried in my local server based on your input in image.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 100
#define WORDLEN 20
int main() {
int place_1, place_2, count = 0, i, k =0;
char str[] = "Hi, welcome to C programming";
char **words = (char **)malloc(sizeof(char *)*SIZE);
if(!words){
printf("malloc of words failed!\n");
exit(1);
}
char *temp = (char *)malloc(sizeof(char)*WORDLEN);
if(!temp){
printf("malloc of temp failed!\n");
exit(1);
}
for(i = 0; str[i] != '\0'; count++){
words[count] = (char *)malloc(sizeof(char)*WORDLEN);
if(!words[count]){
printf("malloc of words[%d] failed!\n", count);
exit(1);
}
sscanf(str+i, "%s", words[count]);
i += 1+strlen(words[count]);
printf("%d %s %d\n", count, words[count], i);
}
printf("Enter the word places to replace: ");
if(scanf("%d %d", &place_1, &place_2) < 2){
printf("scanf failed!\n");
exit(1);
}
temp = words[place_1 - 1];
words[place_1 - 1] = words[place_2 - 1];
words[place_2 - 1] = temp;
for(i = 0; i < count; i++){
sprintf(str+k, "%s ", words[i]);
k += 1+strlen(words[i]);
}
printf("str: %s\n", str);
free(temp);
for(i = 0; i < count; i++){
free(words[i]);
}
free(words);
}
Hope it helps.
Related
Hello, my question is: How to print out string 1 and string 2, not only string 2. I am new to dynamically memory allocated. My sample code is below, thanks for your help.
Result expected:
Hello
My name is Ken
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
int n, i;
char *ptr;
printf("How many strings you want to display?: ");
scanf("%d", &n);
ptr = (char*)malloc(n * sizeof(n));
if(ptr == NULL){
printf("Failed to allocate the memory to string!\n");
exit(0);
}
for(i = 0; i < n; i++){
printf("String %d: ", i + 1);
fflush(stdin);
scanf("%[^\n]", ptr);
}
printf("\n");
printf("Strings you entered:\n");
for(i = 0; i < n; i++){
printf("%s\n", ptr);
}
}
Please check the below code. I have marked modified lines with a comment starting with // CHANGE.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// CHANGE - free memory when not needed
void free_memory(char** ptr, int n)
{
if (ptr)
{
int i;
for (i = 0; i < n; i++)
{
if (ptr[i])
{
free(ptr[i]);
}
}
free(ptr);
}
}
int main(){
int n, i;
char **ptr; // CHANGE - make a double pointer - array of strings (imagine rows and columns)
printf("How many strings you want to display?: ");
scanf("%d", &n);
ptr = (char**) malloc(n * sizeof(char*)); // CHANGE - allocate memory based on no. of rows (columns are string characters)
if (ptr == NULL) {
printf("Failed to allocate the memory to string!\n");
exit(1);
}
getchar(); // CHANGE - read the newline character else fgets doesn't work
for (i = 0; i < n; i++) {
ptr[i] = (char*) malloc(256 * sizeof(char)); // CHANGE - allocate memory for each row
printf("String %d: ", i + 1);
if ( fgets(ptr[i], 256 * sizeof(char), stdin) == NULL ) {
printf("Failed to get line input\n");
free_memory(ptr, n);
exit(1);
}
ptr[i][strlen(ptr[i]) - 1] = '\0'; // CHANGE - remove extra newline character at the end
}
printf("\n");
printf("Strings you entered:\n");
for (i = 0; i < n; i++) {
printf("%s\n", ptr[i]); // CHANGE - print each row
}
free_memory(ptr, n);
return 0;
}
First, there are two numbers that should be decided:
the number of strings the user wants to input and
the length of the strings (or the lengths of each string).
Each string will be stored in a char*. And all strings together will be stored in a char**. The length of char** will be your n in this case.
And length of each char* can be decided however you want.
I prefer to use a directive #define to define a constant like 100.
You can also do a global or local variable or just a digit.
Also don't forget to free anything you allocate. Check below for details.
And happy coding!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING_SIZE 100
int main(){
int n, i;
// stores all the strings
char **ptr;
printf("How many strings you want to display?: ");
scanf("%d", &n);
// allocate memory of size (n * size of char*)
ptr = (char**)malloc(n * sizeof(char*));
if(ptr == NULL){
printf("Failed to allocate the memory to string!\n");
// for portability to use EXIT_FAILURE,
// which is defined in the standard library
exit(EXIT_FAILURE);
}
// for each pointer, allocate memory of size (MAX_STRING_SIZE * size of char)
for(i = 0; i < n; i++)
// I should put a validity check here but I'm too lazy...
ptr[i] = (char*)malloc(MAX_STRING_SIZE * sizeof(char));
for(i = 0; i < n; i++){
printf("String %d: ", i + 1);
fflush(stdin);
scanf("%[^\n]", ptr[i]); // use ptr[i]
}
printf("\n");
printf("Strings you entered:\n");
for(i = 0; i < n; i++){
printf("%s\n", ptr[i]); // use ptr[i]
}
// free all of them
for(i = 0; i < n; i++)
free(ptr[i]);
free(ptr);
return 0;
}
I'm trying to write a program that takes a string as an input, and returns any characters in the string which occur more than once, along with how frequently they occur. What I haven't been able to figure out is finding a way to get the program to return "No duplicates found" for strings with no repeating characters.
# include <stdio.h>
# include <stdlib.h>
#include <ctype.h>
# define NO_OF_CHARS 256
char fillCharCounts (unsigned char *str, int *count) {
int i;
for (i = 0; * (str + i); i++)
count[* (str + i)]++;
return 0;
}
void printDups (unsigned char *str) {
int *count = (int *) calloc (NO_OF_CHARS, sizeof (int));
fillCharCounts (str, count);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1)
printf ("\nDuplicate letter: %c, Occurrences: %d", i, count[i]);
/* area of concern */
if (count[i] < 1)
printf ("\nNo duplicates found\n");
exit (0);
printf ("\n");
free (count);
}
int main() {
unsigned char str[15] = "";
printf ("Enter a word>");
scanf ("%s", str);
printDups (str);
getchar();
return 0;
}
The program returns characters that occur more than once along with their frequency, but it always returns "No duplicates found" along with this. How can i fix it so it only returns "No duplicates found" for strings with no repeating characters?
You need to use a flag/counter say dupe_chars to track if one or more duplicate characters were found.
int dupe_chars = 0; // an integer flag/counter
for (int i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1) {
printf ("\nLetter: %c, Occurrences: %d", i, count[i]);
++dupe_chars; //counting duplicate letters
}
/* area of concern */
if (0 != dupe_chars)
printf ("\nDuplicates of %d chars were found\n", dupe_chars);
else
printf ("\nNo duplicates were found\n");
//exit (0); // not necessary
This is the code I am not able to fix it. It works fine if 5 or more characters are used but using less than 4 characters breaks it.
#include <stdio.h>
void main()
{
char str[1000], rev[1000];
int i, j, count = 0;
printf("Enter the string :");
scanf("%s", str);
printf("\nString Before Reverse: %s", str);
while (str[count] != '\0')
{
count++;
}
j = count-1 ;
for (i = 0; i<count; i++)
{
rev[i] = str[j];
j--;
}
printf("\nString After Reverse: %s", rev);
}
Your have to null terminate your rev string like:
rev[count] = '\0';
Also, please make your code more readable.
I need help about this exam.I need to reverse the input string.
int main(void)
{
char str[30];
int strlen; int i=0; int count=0;int temp;int j;
printf("Enter the string \n");
gets(str);
while(str[i]!='\0')
{
i++;
count++;
}
strlen=count;
printf("The length of the string:%d\n", strlen);
i=0;
j=strlen;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reverse string :%s",str);
return 0;
}
The problem is that at the end its not show me the string.
It shows me :
"Reverse string :"
and that is, no reverse string. Where is my mistake?
In your code you are doing
j=strlen;
j points to the last index of the string which will be '\0'
And later in the loop you set str[i]=str[j];
Therefore, the first index will be \0
Printing str will display nothing
In order to make the code correct set j=strlen - 1;
Try this:-
As In your code you are assigning j=strlen pointing to \0 or null character change it to j=strlen-1;
char str[30];
int strlen;int i=0;int count=0;int temp;int j;
printf("Enter the string \n");
gets(str);
while(str[i]!='\0')
{
i++;
count++;
}
strlen=count;
printf("The lenht of the string:%d\n",strlen);
i=0;
j=strlen-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reverse string :%s",str);
The problem is with the assignment j=strlen;'.
People will suggest you to change it toj=strlen - 1;`
But, I'll recommend to resolve at its root.
while(str[i]!='\0')
{
i++;
count++;
}
After this loop, count will hold value as the index which has a '\0' of the string. Here, you should decrement count and then assign it to strlen. That makes the code more understandable.
With this change, you'll also have to change
printf("The length of the string: %d\n", strlen);
to
printf("The length of the string: %d\n", strlen+1);
as it would print
The length of the string: 4
instead of 5 for "Hello" because of the decrement.
Additionally, strlen is a function once you include string.h header file in your code. To keep it portable, you should always use naming convention which won't have standard, common function names (such as strlen) as a variable name in your code.
A slightly better version (using purely your logic) than your existing code will use one variable less, and will look like this:
#include<stdio.h>
int main(void)
{
//char str[30] = "Hello";
char str[30] = { [0 ... 29] = 0 };
//int str_length = 0;
int i = 0, count = 0, j = 0;
char temp = 0; //This should be a char rather than an int
printf("Enter the string \n");
gets(str);
while(str[i]!='\0')
{
i++;
count++;
}
printf("The length of the string: %d\n", count);
if(count) count--;
//str_length = count;
i = 0;
j = count;
while(i < j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reverse string :%s", str);
return 0;
}
I need to compare tokens.
I need to know two tokens which are equal.
This is my code. And something is going wrong when comparing- compilator just crashes.
Can you help me to find error?
int main()
{
int i=0;
char* words[200];
char text[200];
printf("Enter one sentence \n ");
gets(text);
char *word = strtok(text, " ");
while(word!=0)
{
words[i++] = strdup(word);
printf("[%s]\n", word);
word=strtok(NULL, " ,.!?");
}
for (k=0; k<199; k++)
{
for (j=k+1; j<200; j++)
{
if (strcmp(words[k],words[j])==0)
{
printf("Equal words are %s",words);
}
else
{
printf("In this sentence aren't equal words");
}
}
}
getch();
return 0;
In your for loops you iterate until 200, not until the max number of entered words (i) is reached.
There is no guarantee which value the elements of an uninitialized array will have at runtime. They might be 0, but also might be any other random numbers. Which means, that doing strcmp with any array element beyond the number of entered words will result in undefined behavior.
Do your nested for-loop like this:
for (k=0; k < i-1; k++)
{
for (j=k+1; j < i; j++)
{
...
}
}
I realize this is an old question, but I found #elgonzo's answer helpful and was able to get your program to compile after a few other changes. I added the libraries, added \n to the print statements, and initialized the variables k and j which may have been part of your problem.
Here's my version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i=0, k=0, j=0;
char* words[200];
char text[200];
printf("Enter one sentence \n ");
gets(text);
char *word = strtok(text, " ");
while(word!=0)
{
words[i++] = strdup(word);
printf("[%s]\n", word);
word=strtok(NULL, " ,.!?");
}
for (k=0; k < i-1; k++)
{
for (j=k+1; j < i; j++)
{
if (strcmp(words[k],words[j])==0)
{
printf("Equal words are %s\n", *words);
}
else
{
printf("In this sentence aren't equal words\n");
}
}
}
return 0;
}