replacement of string from a string by a character - c

how to code a user defined function that searches and replaces a character occurrences of any of the character contained in another string with a character string.
Cannot used any string variable in the code, has to be a user defined function.
Thanks
This is what i have tried so far
#define _CRT_SECURE_NO_WARNINGS
#include
#include
void s1();
void s2();
int main(void)
{
int i=0;
s1();
s2();
printf("c = {'$'} ");
}//main
void s1(){
int i = 0;
while (i <= 40){
printf("%c", (rand() % 25) + 'A');
i++;
}
}
void s2(){
char s2[20];
printf("\nEnter a string of minimum 2 and maximum 20 characters= ");
gets(s2);
puts(s2);
}
/*
I just need to make another function that searches s1 and replaces any occurrence of any of the character contained is s2 with a character that can be anything(e.g. '$')
*/

//If I have understood your question then this should be answer
char *replace(char [] a, char b[], int lower, int upper){
char c[100];
int j = 0;
for(int i = 0; i < lower; i++){
c[j] = a[i];
j++;
}
for(int i = 0; i < strlen(b); i++){
c[j] = b[i];
j++;
}
for(int i = upper; i < strlen(a); i++){
c[j] = a[i];
j++;
}
c[j] = '\0'
for(int i = 0; i < strlen(c); i++){
a[i]= c[i];
}
a[i] = '\0';
return a;
}

Related

Unexpected results while printing a string

I created a program in which i declared two arrays of char type. One would store the string and another would store the reversed string.But when i print the second array it displays some unexpected results.
#include<stdio.h>
main(){
char a[] = "Sahib";
char b[5];
int i = 0;
int j,k = 0;
char c='a';
while(c!='\0'){
c = a[i];
i++;
}
i -= 2;
for(j=i;j<=0;j--){
b[k] = a[j];
k++;
}
printf("The reversed character is %s",b);
}
try this:
#include <stdio.h>
int main(void){
char a[] = "Sahib";
char b[sizeof a];
int i = 0;
int j,k = 0;
char c;
while((c = a[i]) != '\0'){
i++;
}
for(j = --i; j>=0; --j){
b[k++] = a[j];
}
b[k] = '\0';
printf("The reversed character is %s\n", b);
return 0;
}

obtaining ASCII values of input chars in c

I was intending to create a simple function that would take a string as its input and output the equivalent of that string in ASCII. Plz help..
void cls(){
system("cls");
}
void getAscii(){
cls();
text(4);
char a[94]={' ','!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','#',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',"'\'",']','^','_','`','a','b',
'c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~'};
while(1){
char x[5000], *exitMsg = "quit";
gets(x);
if(strcmp(x, exitMsg) == 0){
break;
}else{
int i = 0;
for(i = 0; i < strlen(x); i++){
int j = 0;
for(j = 0; j < 94; j++){
if(x[i] == a[j]){
int xa = (a[j] + 32);
printf("%d", &xa);
}
}
}
printf("\n");
}
}
}
A char is just an one byte number. When it represents an ascii character it is actually just the number for it. For example when you say char x = 'A', you are essentially saying char x = 65. The one byte in memory representing x really stores the number 65. If you did x+1 you would get 66 or 'B' depending on how you print it. When you tell it to print a char it will look up the ascii table and print the character. If you tell it to print a decimal it will print 65. For example:
char x = 'A';
printf("%d", x);
This will print 65. You do not need a conversion table to look up the ascii values.
No need for ascii arrays and another loop inside your code.
This
for(i = 0; i < strlen(x); i++){
int j = 0;
for(j = 0; j < 94; j++){
if(x[i] == a[j]){
int xa = (a[j] + 32);
printf("%d", &xa);
}
}
}
can be simplified to
for(i = 0; i < strlen(x); i++) {
printf("%d", x[i]);
}
There are a few errors in your code :
You have used "" a few times instead of ''. Correct this.For special situations use the escape sequence i.e, for writing the \ character use '\\' or for ' character use '\''.
The total number of elements are 95 not 94.
Remove &xa from printf and use xa.
No Need of adding 32 to xa.
The corrected code is:
#include<stdio.h>
#include<process.h>
#include<string.h>
void cls(){
system("cls");
}
void Ascii(){
cls();
// text(4); //uncomment this if it does something useful
char a[95]={' ','!','"','#','$','%','&',' ','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','#',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_','`','a','b',
'c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~'};
while(1){
char x[5000], *exitMsg = "quit";
gets(x);
if(strcmp(x, exitMsg) == 0){
break;
}else{
int i = 0;
for(i = 0; i < strlen(x); i++){
int j = 0;
for(j = 0; j < 94; j++){
if(x[i] == a[j]){
int xa = (a[j] );
printf("%d ", xa);
}
}
}
printf("\n");
}
}
}
ALTHOUGH You require none of this.
Try this:
void cls(){
system("cls");
}
void Ascii(){
cls();
while(1){
char x[5000], *exitMsg = "quit";
gets(x);
if(strcmp(x, exitMsg) == 0){
break;
}else{
int i = 0;
for(i = 0; i < strlen(x); i++){
int xa = (x[i] );
printf("%d ", xa);
}
}
printf("\n");
}
}

Duplicate Characters Removal - From O(n^2) to O(n)

C program for removal of duplicate characters from the given string. It uses the O(n2) can we do it in O(n) order. Please comment on this program.
int main()
{
char a[100],b[100],temp='\0';
int i,n,j,count=0,p=0,k=0;
printf("ENTRE THE STRING \n");
scanf("%s",a);
n = strlen(a);
i=0;
while(i < n)
{
count=0;
temp = a[i];
for(j = i ; j < n ; j++ )
{
if(temp==a[j])
{
count++;
}
}
if(count<2)
{
b[k] = temp;
k++;
}
i++;
}
b[k]='\0';
printf("THE RESULTED STRING IS \n");
for(p = 0 ; p < k ; p++)
printf("%c ",b[p]);
printf("\n");
return 0;
}
You can create a O(n) algorithm for this.
Steps:
Create another array bucket[] with size 255. (Should adjust all the characters)
Initialise every element in bucket[] to 0.
Run a loop and increment the bucket[] at the index a[i].
Now, run another loop through the bucket[], if bucket[i] > 0, append the (char) i to the b[] array.
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
int bucket[256] = {0};
int i;
printf("Enter the string:");
scanf("%s",a);
int n = strlen(a);
for(i = 0; i < n; ++i)
{
//Incrementing the character count of each character.
bucket[a[i]]++;
}
//Keep track of the index where the next character is to be appended.
int b_pos = 0;
for (i = 0; i < 256; ++i)
{
//Character occurs in a[], we don't care if it occurs once
//or twice, we just need one instance of it.
if (bucket[i] > 0)
{
b[b_pos] = (char) i;
b_pos++;
}
}
b[b_pos] = '\0';
printf("Modified string : %s",b);
}
Take a look at this:
int main()
{
char a[100],b[100];
int i,n,j,count=0,k=0;
printf("ENTRE THE STRING \n");
scanf("%s",a);
n = strlen(a);
b[0] = a[0];
k = 1;
for(i=1;i<n;i++)
{
for(j=0;j<i;j++)
{
if(a[i] == b[j])
{
count = 1;
break;
}
}
if(count == 0)
{
b[k] = a[i];
k++;
}
else
{
count = 0;
}
}
b[k] = 0;
printf("RESULT %s",b);
return 0;
}

Messing with Character Arrays in C

Can someone advise why the loop in the main dies after the fifth iteration never completing
it's intended goal of reducing the character array down to 1 final element? I've gotten it this
far and am completely consumed as their should be 11 iterations as returned by the call
size_t strlen( char const *str )
{
int length = 0;
while (*str++ !='\0')
{
length += 1;
}
return length;
}
void abracadabra( char *word )
{
int i, c;
int len = strlen(word)-1;
for (i = 0; i <= len; i++)
{
putchar(*word);
putchar(' ');
*(word++);
}
}
int main()
{
char word[250];
int i, j;
printf ("enter your word:\n");
scanf ("%[^\n]s", &word);
for (i = 0; i <= strlen(word)-1; i++)
{
abracadabra(word);
putchar('\0');
printf("\n");
for (j = 0; j <= i; j++)
{
putchar('\0');
}
word[strlen(word) - 1] = '\0';
}
word[strlen(word)-1] = '\0';
printf("\n");
system("pause");
return 0;
}
Each time you execute the outer for loop in main the size of the string decreases by 1. The counter i is also increasing by 1 each time. This causes you to run the loop half of the times that you intend to.
int size = strlen(word);
for (i = 0; i < size; i++) {
\\same inner code
}
Subbing the above code for the outer for loop in main resolves the issue.
The is mistake in using the variable i and strlen in for loop. i is keep increasing and word length is decreasing. So in the mid, loop is terminated due to i>strlen (word)
int main()
{
char word[250];
int i, j;
printf ("enter your word:\n");
scanf ("%[^\n]s", &word);
// for (i = 0; i <= strlen(word)-1; i++)
while ( strlen(word) )
{
abracadabra(word);
putchar('\0');
printf("\n");
word[strlen(word) - 1] = '\0';
}
word[strlen(word)-1] = '\0';
printf("\n");
system("pause");
return 0;
}

string reverse with loop and array in c

I just want to reverse a string using for loop and array. Don't want to use any predefined function. I used the following code but its near to nothing. Please share some good suggestions.
int main(){
char a[]="this is a man";
char b[30];
int p= sizeof(a)/sizeof(a[0]);
for(int i=p-1;i>0;i--){
for(int j=0;j<p;j++){
b[j]=a[i];
}
}
printf("array is %s",b);
return 0;
}
#include<stdio.h>
int main(){
char str[] = "str to rev";
char revstr[12]={'\0'};
int i, j;
int length = strlen(str);
j = 0;
for(i = length-1; i>=0; i--){
revstr[j] = str[i];
j = j + 1;
}
printf("%s", revstr);
return 0;
}
1) In your first for loop, you have to reach 0 (i>=0)
for(int i=p-1;i>=0;i--){
2) The a[p-1] contains the null termination('\0') of your string a[]. And the null termination should not be included in the array reverse procedure. So in your first loop you should start from p-2 and not from p-1.
And after finishing the reversing you have to add a '\0' (null terminator) at the end of your b array
b[j]='\0'; // add this
printf("array is %s",b);
return 0;
3) And as said in the other answers, you have to use only one loop and not 2 loops.
int i,j;
for (i=p-2, j=0; i>=0; i--,j++) {
b[j]=a[i];
}
b[j]='\0';
printf("array is %s",b);
Using while loop::
void main()
{
char str[100],temp;
int i,j=0;
printf("nEnter the string :");
gets(str);
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("nReverse string is :%s",str);
return(0);
}
Using for loop::
void StrRev(char *str)
{
int i, len, endpos;
len = strlen(str);
endpos = len-1;
for(i = 0; i < len / 2; i++)
{
char temp = str[i];
str[i] = str[endpos - i];
str[endpos - i] = temp ;
}
}

Resources