Substring replacement in a string in C [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
everyone! I decided to make an account on this site seeking for help because I could not find anything that can help me. I have a problem which requires multiple steps:
1) Read a string from keyboard;
2) Read an integer that represents the number of substrings that you want to modify ( By modifying it means to transform all of the characters of the string into " * " );
3)Read all of the substrings that need to be modified;
4) Print the initial string modified.
I tried to make it with little steps by firstly managing to do it with one substring, but I don't know how to do it when I read multiple substrings. So, here are the versions
VERSION 1
#include<stdlib.h>
#include<string.h>
int main()
{
int n;
char str[5120];
char substr[100];
printf("Type the string:\n");
gets(str);
printf("\nType the substring which you would like to modify:");
gets(substr);
char *p;
p = strstr(str,substr);
if (*p != '\0')
{
for( int j=0 ; j< strlen(substr); j++)
{
*p = '*';
p++;
}
}
printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(a) ; i++)
{
printf("%c",a[i]);
}
return 0;
}
AND THE VERSION IN WHICH I TRIED TO MODIFY MULTIPLE
#include<stdlib.h>
#include<string.h>
int main()
{
int n;
char str[5129];
char substr[n][100];
printf("Type the string:\n");
gets(str);
printf("How many substrings to modify?");
scanf("%d",&n);
printf("\nType the substrings:");
for( int i=0 ; i< n ; i++)
{
scanf("%s",substr[i]);
printf(" ");
}
for ( int i=0; i < n; i++)
{
char *p;
p = strstr(str,substr[i]);
if (*p != '\0')
{
for( int j=0 ; j< strlen(cuv[i]); j++)
{
*p = '*';
p++;
}
}
}
printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(str) ; i++)
{
printf("%c",str[i]);
}
return 0;
}```
I guess for the n times that I cycle to the string I have to allocate memory somewhere, or I don't know..
Please, I need some help! Thank you!

So I edited my answer based on your and #PaulOgilvie suggestions. I hope that the program now works as you expected.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 5129
void replaceSubstring(char *p, int len){
for(int i = 0; i < len; i++, p++){
*p = '*';
}
}
int main() {
int n = 0;
char str[MAX_SIZE];
char substr[n][100];
printf("Type the string:\n");
fgets(str, MAX_SIZE, stdin);
printf("How many substrings to modify?");
scanf("%d",&n);
for( int i=0 ; i< n ; i++) {
printf("\nType the substring number %d:", i+1);
scanf("%s",substr[i]);
}
char *p;
for ( int i=0; i < n; i++){
p = strstr(str, substr[i]);
while(p != NULL) {
replaceSubstring(p, strlen(substr[i]));
p = strstr(str, substr[i]);
}
}
printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(str) ; i++)
{
printf("%c",str[i]);
}
return 0;
}

Related

Split array by space into words

I got this code right here, which works.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100] = "Hello how are you";
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
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;
}
but instead of char str1[100] I want to use an array of sentenceschar str1[2][100]
Meaning
char str1[2][100] = {"Hello how are you","I'm good, thanks"}
And these two sentences (or more) I want to be separated in separate words
char str1[100] = {"Hello","how","are","you"};
Actually, this is from a project for school, in which from a file, i have to store each sentence ended by '.'
If there is another way to store each sentece directly as words instead of sentences, it would be great help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LSIZ 128
#define RSIZ 10
void yodificacio(char* arr[], int index[], int n)
{
char* temp[n];
// arr[i] should be present at index[i] index
for (int i=0; i<n; i++){
temp[index[i]] = arr[i];
}
// Copy temp[] to arr[]
for (int i=0; i<n; i++)
{
arr[i] = temp[i];
index[i] = i;
}
}
int main()
{
int i = 0;
char *arr[] = {"Hey","there","how","are","you","all","today","idk"}; **Here I want the input to be char str1[2][100] = {"Hello how are you", "Im good thanks}, instead of char arr[] ...**
int index[] = {0,2,1,4,5,3,6,7};
int n = sizeof(arr)/sizeof(arr[0]);
yodificacio(arr, index, n);
printf("Reordered array is: \n");
for (int i=0; i<n; i++)
printf ("%s ", arr[i]);
return 0;
return 0;
}
Add an outer loop to process each sentence in the array.
int main()
{
char str1[2][100] = {"Hello how are you","I'm good, thanks"} ;
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
j=0; ctr=0;
for (int k = 0; k < sizeof(str1) / sizeof(str1[0]); k++) {
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[k][i]==' '|| str1[k][i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[k][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;
}

why is my function encodeChar does not work?

The code below is supposed to allow the user to enter two character strings s and t, an array of structures and the size
of array as parameters, encodes the characters in s to t, and passes the encoded string t to the caller via call by reference.
I cannot understand why my function encodeChar is wrong. I have already tried to use the indexing method and it is similar to the correct answer. But when i input
1
3
a
b
b
c
c
d
3
abcd
4
, the output is abdd. I do not understand where is my mistake. Please have me resolve my misconceptions.
#include <string.h>
typedef struct {
char source;
char code;
} Rule;
void createTable(Rule *table, int *size);
void printTable(Rule *table, int size);
void encodeChar(Rule *table, int size, char *s, char *t);
int main()
{
char s[80], t[80], dummychar, *p;
int size, choice;
Rule table[100];
printf("Select one of the following options:\n");
printf("1: createTable()\n");
printf("2: printTable()\n");
printf("3: encodeChar()\n");
printf("4: exit()\n");
do {
printf("Enter your choice: \n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("createTable(): \n");
createTable(table, &size);
break;
case 2:
printf("printTable(): \n");
printTable(table, size);
break;
case 3:
scanf("%c",&dummychar);
printf("Source string: \n");
fgets(s, 80, stdin);
if (p=strchr(s,'\n')) *p = '\0';
encodeChar(table,size,s,t);
printf("Encoded string: %s\n", t);
break;
default:
break;
}
} while (choice < 4);
return 0;
}
void printTable(Rule *table, int size)
{
int i;
for (i=0; i<size; i++)
{
printf("%d: %c->%c\n", i+1, table->source, table->code);
table++;
}
}
void createTable(Rule *table, int *size)
{
/*edit*/
/* Write your code here */
/*edit*/
/* Write your code here */
int i;
char dummy[80];
printf("Enter number of rules: \n");
scanf("%d", size); // dont careless here
for(i=0; i< *size; i++){
printf("Enter rule %d: \n", i+1);
fgets(dummy, 80,stdin); // why need to use this twice
printf("Enter source character: \n");
scanf("%c", &table[i].source);
fgets(dummy,80,stdin);// why
printf("Enter code character: \n ");
scanf("%c", &table[i].code);
}
/*end_edit*/
/*end_edit*/
}
void encodeChar(Rule *table, int size, char *s, char *t)
{
/*edit*/
/* Write your code here */// this is wrong
int i, j;
for(i = 0 ; s[i] != '\0'; i++){
for(j = 0; j < size; j++){
if(s[i] == table[j].source){
*t = table[j].code;
}
else{
*t = s[i];
}
}
t++;
}
*t = '\0';
/*edit*/
/* this is correct
int i;
while(*s!='\0'){
for(i = 0; i < size; i++){
if(*s != table[i].source)
*t = *s;
else
*t = table[i].code;
t++;
s++;
}
}
*t = '\0';
*/
}
Here a paper sheet and a pencil would be enough.
Just follow your code for abcd. The relevant part is
for(i = 0 ; s[i] != '\0'; i++){
for(j = 0; j < size; j++){
if(s[i] == table[j].source){
*t = table[j].code;
}
else{
*t = s[i];
}
}
t++;
}
*t = '\0';
Let's go:
i is 0, s[i] is a
j is 0, table[j].source is a: *t receives b
j is 1, table[j].source is b: *t recieves (back) a !...
Only the last rule can be applied with your code...
A simple fix would be to break out of the loop when a rule is applied to prevent the following ones to roll back the change:
for(i = 0 ; s[i] != '\0'; i++){
for(j = 0; j < size; j++){
if(s[i] == table[j].source){
*t = table[j].code;
break; // do not examine other rules
}
else{
*t = s[i];
}
}
t++;
}
*t = '\0';
But if the same character is changed by multiple rules, this code would use the first one, while the correct code would use the last one, so this would be more consistent:
for(i = 0 ; s[i] != '\0'; i++){
for(j = size-1; j >= 0; j--){ // examine rules in descending order
...
Anyway, there are still possible improvements here, so you could probably post it to CodeReview for advices for best practices...

rearranging a char array with strncpy in C

I am trying to change the sorting of a the arr list which could consist of zero, one, two as the inputted and stored values for arr. The stringreplace function is meant to shift every single element by one so the new sorting would be one, two, zero. I am trying to replace the elements with one another by using the strncpy function but I think it is a bit faulty, how could i fix this?
strncpy function
char stringreplace( char a[], int b){
for(int j = 0; j > b -1; j++){
strncpy(a[j], a[j+1], sizeof(a));}
for(int j = 0; j > b; j++){
printf("%s",a[j]);}
}
main function
int main()
{
char input[100];
char arr[100]= {0};
int number;
printf("Input the number of strings: ");
scanf("%d", &number);
for(int i= 0; i < number; i++){
printf("Input the number of strings: ");
scanf("%s", input);
arr[i] = input;
}
stringreplace(arr, number);
return 0;
}
You may consider allocating strings dynamically, assigning a pointer for each string into an array words, and then rotating each pointer in the array to the left.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void lrot_words(char *words[], int n);
int main(void)
{
char *p, word[100], *words[100];
int i, num_words;
printf("Enter the number of words: ");
scanf("%d", &num_words);
for(i = 0; i < num_words; i++){
printf("Enter a word: ");
scanf("%s", word);
if ((p = malloc(strlen(word) + 1)) == NULL) {
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
words[i] = strcpy(p, word);
}
lrot_words(words, num_words);
for (i = 0; i < num_words; i++) {
printf("%s\n", words[i]);
}
return 0;
}
void lrot_words(char *words[], int n)
{
char *temp = words[0];
int i;
for (i = 0; i < n - 1; i++) {
words[i] = words[i+1];
}
words[i] = temp;
}

Compare tokens with strcmp

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;
}

how to store and then print a 2d character/string array?

Suppose I have the words: tiger, lion, giraffe.
How can I store it in a two dimensional char array using for loop and scanf and then print the words one by one using a for loop?
Something like
for(i=0;i<W;i++)
{
scanf("%s",str[i][0]); //to input the string
}
PS Sorry for asking such a basic question, but I couldn't find a suitable answer on Google.
First you need to create an array of strings.
char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];
Then, you need to enter the string into the array
int i;
for (i=0; i<NUMBER_OF_WORDS; i++) {
scanf ("%s" , arrayOfWords[i]);
}
Finally in oreder to print them use
for (i=0; i<NUMBER_OF_WORDS; i++) {
printf ("%s" , arrayOfWords[i]);
}
char * str[NumberOfWords];
str[0] = malloc(sizeof(char) * lengthOfWord + 1); //Add 1 for null byte;
memcpy(str[0], "myliteral\0");
//Initialize more;
for(int i = 0; i < NumberOfWords; i++){
scanf("%s", str[i]);
}
You can do this way.
1)Create an array of character pointers.
2)Allocate the memory dynamically.
3)Get the data through scanf. A simple implementation is below
#include<stdio.h>
#include<malloc.h>
int main()
{
char *str[3];
int i;
int num;
for(i=0;i<3;i++)
{
printf("\n No of charecters in the word : ");
scanf("%d",&num);
str[i]=(char *)malloc((num+1)*sizeof(char));
scanf("%s",str[i]);
}
for(i=0;i<3;i++) //to print the same
{
printf("\n %s",str[i]);
}
}
#include<stdio.h>
int main()
{
char str[6][10] ;
int i , j ;
for(i = 0 ; i < 6 ; i++)
{
// Given the str length should be less than 10
// to also store the null terminator
scanf("%s",str[i]) ;
}
printf("\n") ;
for(i = 0 ; i < 6 ; i++)
{
printf("%s",str[i]) ;
printf("\n") ;
}
return 0 ;
}

Resources