Write a function to replace certain characters('., ') in a string with a special character('|').
Example,
Input => "Hey, I am a rockstar.....yeah"
Output => "Hey|I|am|a|rockstar|yeah"
Alternative:
Write an algorithm to replace all spaces in a given string with ‘%20′. You can consider that string has enough space at the end of the string to hold the extra characters.
http://algorithms.tutorialhorizon.com/replace-all-spaces-in-a-string-with/
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int hasCh(char *str, char ch)
{
int len = strlen(str);
int i = 0;
for(i=0; i < len; i++)
{
if(str[i] == ch)
return 1;
}
return 0;
}
void replace(char *str, char *delimit)
{
int len = strlen(str);
int cur = 0;
int flag = 0;
int i = 0;
for(i=0; i< len; i++)
{
if(hasCh(delimit, str[i]))
{
if(!flag)
{
flag = 1;
str[cur] = '|';
cur++;
}
}
else
{
flag = 0;
str[cur] = str[i];
cur++;
}
}
str[cur] = '\0';
}
int main()
{
char str[50] = {0, };
sprintf(str, "%s", "Hey, I am a rockstart...yeah");
replace(str, ", .");
printf("%s\n", str);
return 0;
}
Example,
Input => "Hey, I am a rockstar.....yeah"
Output => "Hey|I|am|a|rockstar|yeah"
Alternative:
Write an algorithm to replace all spaces in a given string with ‘%20′. You can consider that string has enough space at the end of the string to hold the extra characters.
http://algorithms.tutorialhorizon.com/replace-all-spaces-in-a-string-with/
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int hasCh(char *str, char ch)
{
int len = strlen(str);
int i = 0;
for(i=0; i < len; i++)
{
if(str[i] == ch)
return 1;
}
return 0;
}
void replace(char *str, char *delimit)
{
int len = strlen(str);
int cur = 0;
int flag = 0;
int i = 0;
for(i=0; i< len; i++)
{
if(hasCh(delimit, str[i]))
{
if(!flag)
{
flag = 1;
str[cur] = '|';
cur++;
}
}
else
{
flag = 0;
str[cur] = str[i];
cur++;
}
}
str[cur] = '\0';
}
int main()
{
char str[50] = {0, };
sprintf(str, "%s", "Hey, I am a rockstart...yeah");
replace(str, ", .");
printf("%s\n", str);
return 0;
}
No comments:
Post a Comment