Whitespace replace in C language - c

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'.

Related

Remove multiple characters from string

I'm trying to creat a program that removes all occurences from a character that I choose from a certain string and also returs the number of characters that were removed.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIMV 10
int eliminar(char texto[], char ch, char novoTexto[]){
int a=0,i;
for(i=0; texto[i] != '\0';i++){
texto[i] = texto[i+a];
novoTexto[i]=texto[i];
if(novoTexto[i]==ch){
novoTexto[i] = '\0';
a++;
}
}
return a;
}
int main()
{
char frase[]="Uma arara torta!";
char res[50];
printf("%s\n",frase);
printf("%d\n",eliminar(frase,'r',res));
printf("%s\n",res);
return 0;
}
When I run the program, it returns:
Uma arara torta!
3
Uma a
What I wanted to return is:
Uma arara torta!
3
Uma aaa tota!
It's a silly question but I can't find the mistake that I made. Thank you!
Putting '\0' means to terminate the string there.
You have to skip adding characters to eliminate.
Try this:
int eliminar(char texto[], char ch, char novoTexto[]){
int a=0,i,j=0;
for(i=0; texto[i] != '\0';i++){
if(texto[i]==ch){
a++;
}else{
novoTexto[j]=texto[i];
j++;
}
}
novoTexto[j]='\0';
return a;
}
Putting '\0' means to terminate the string there.
check this:
int eliminator(char * texto, char ch, char * novoTexto) {
int i=0;
while(*texto != '\0') {
if (*texto == ch) {
texto++;
++i;
} else {
*novoTexto++ = *texto++;
}
}
*novoTexto = '\0';
return i;
}
int main(int arg, char **argv) {
char frase[] = "Uma arara torta!";
char res[50];
printf("%s\n",frase);
printf("%d\n",eliminator(frase, 'r', res));
printf("%s\n",res);
}

How do I check if a string contains a certain character?

I'm fairly new to C programming, how would I be able to check that a string contains a certain character for instance, if we had:
void main(int argc, char* argv[]){
char checkThisLineForExclamation[20] = "Hi, I'm odd!"
int exclamationCheck;
}
So with this, how would I set exclamationCheck with a 1 if "!" is present and 0 if it's not? Many thanks for any assistance given.
By using strchr(), like this for example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Hi, I'm odd!";
int exclamationCheck = 0;
if(strchr(str, '!') != NULL)
{
exclamationCheck = 1;
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}
Output:
exclamationCheck = 1
If you are looking for a laconic one liner, then you could follow #melpomene's approach:
int exclamationCheck = strchr(str, '!') != NULL;
If you are not allowed to use methods from the C String Library, then, as #SomeProgrammerDude suggested, you could simply iterate over the string, and if any character is the exclamation mark, as demonstrated in this example:
#include <stdio.h>
int main(void)
{
char str[] = "Hi, I'm odd";
int exclamationCheck = 0;
for(int i = 0; str[i] != '\0'; ++i)
{
if(str[i] == '!')
{
exclamationCheck = 1;
break;
}
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}
Output:
exclamationCheck = 0
Notice that you could break the loop when at least one exclamation mark is found, so that you don't need to iterate over the whole string.
PS: What should main() return in C and C++? int, not void.
You can use plain search for ! character with
Code
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Hi, I'm odd!";
int exclamationCheck = 0;
int i=0;
while (str[i]!='\0'){
if (str[i]=='!'){
exclamationCheck = 1;
break;
}
i++;
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}

C function to capitalize the first character of a pointer string

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"

How to display the word and its number of occurences in a string in C

Basically, I want to display the words and their number of occurrences in a string. It can be both case sensitive and vice-versa.
For e.g if the input string is "Hello World How are you Hello how", the output should be:
Hello,2
World,1
How,2
are,1
you,1
I am not able to figure out the logic for this yet; any help?
Use
fgets()
strtok_r()
strcmp()
Check these three APIs. Figure out the code-to-write, implement, run into issues, come back and we'll be here to help.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
bool eq(const char *s, const char *w, char ignore_case){
char si, wi;
while(*w && !isspace(*w)){
if(ignore_case != 'n'){
si = tolower(*s++);
wi = tolower(*w++);
} else {
si = *s++;
wi = *w++;
}
if(si != wi)
return false;
}
return !*s || isspace(*s);
}
char *next_word(char *w){
while(*w && !isspace(*w))
++w;
if(!*w)
return w;
while(isspace(*w))
++w;
return w;
}
int main() {
char ignore_case = 'n';
char *word, *str;
char string[128];
printf("ignore case ?(y/n):");
scanf("%c", &ignore_case);
printf("input string : ");
scanf(" %127[^\n]", string);
str = string;
while(*str){
int counter = 1;
word = next_word(str);//skip first word
while(*word){
char *p = NULL;
if(eq(str, word, ignore_case)){
p = word;
++counter;
}
word = next_word(word);//move to next word top
if(p)
memset(p, ' ', word - p);//clear already match word
}
word = str;
str = next_word(str);
while(*word && !isspace(*word))
putchar(*word++);
printf(",%d\n", counter);
}
return 0;
}

string parsing occurrence in c

I have a string as const char *str = "Hello, this is an example of my string";
How could I get everything after the first comma. So for this instance: this is an example of my string
Thanks
You can do something similar to what you've posted:
char *a, *b;
int i = 0;
while (a[i] && a[i] != ',')
i++;
if (a[i] == ',') {
printf("%s", a + i + 1);
} else {
printf("Comma separator not found");
}
Alternatively, you can take a look at strtok and strstr.
With strstr you can do:
char *a = "hello, this is an example of my string";
char *b = ",";
char *c;
c = strstr(a, b);
if (c != NULL)
printf("%s", c + 1);
else
printf("Comma separator not found");
Since you want a tail of the original string, there's no need to copy or modify anything, so:
#include <string.h>
...
const char *result = strchr(str, ',');
if (result) {
printf("Found: %s\n", result+1);
} else {
printf("Not found\n");
}
If you want ideas how to do it yourself (useful if you later want to do something similar but not identical), take a look at an implementation of strchr.
const char *result;
for(result = str; *result; result++)
if(*result == ',')
{
result++;
break;
}
//result points to the first character after the comma
After this code, result points to the string starting right after the comma. Or to the final '\0' (empty string), if there is no comma in the string.
You have the right idea, the following programs is one way to do it:
#include <stdio.h>
#include <string.h>
static char *comma (char *s) {
char *cpos = strchr (s, ',');
if (cpos == NULL)
return s;
return cpos + 1;
}
int main (int c, char *v[]) {
int i;
if (c >1 )
for (i = 1; i < c; i++)
printf ("[%s] -> [%s]\n", v[i], comma (v[i]));
return 0;
}
It produced the following output:
$ commas hello,there goodbye two,commas,here
[hello,there] -> [there]
[goodbye] -> [goodbye]
[two,commas,here] -> [commas,here]

Resources