This is a simple sorting code:
#include <stdio.h>
int main(void) {
int i, j;
char str[] = "Hello!! How are you?? I'm Fine. No Thank you.", temp;
for (i = 0; i < sizeof(str); i++) {
for (j = i + 1; j < sizeof(str); j++) {
if (str[i] > str[j]) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
}
for(i = 0; i < sizeof(str); i++)
printf("%c", str[i]);
printf("%s", str);
}
I found out that I'm able to print the sorted string character by character through for loop but not printf("%s", str);, it wouldn't print anything, can someone tell me why and how to solve this?
You compute the size of your string as sizeof(str). That includes the trailing \0. The byte \0 is guaranteed to end up at the beginning of your sorted string, telling printf that the string is actually empty. You want to leave the terminating NUL past the end of the string, since it is not part of the buffer that you want to sort.
To sort only the characters of the string, without the terminator, change the loop to
int n = strlen(str);
for(i = 0; i < n; i++) {
for(j = i + 1; j < n; j++) {
You can use the strlen function to calculate length of string.
#include <stdio.h>
#include <string.h>
int main(void) {
int i, j;
char str[] = "Hello!! How are you?? I'm Fine. No Thank you.", temp;
int n = strlen(str);
for(i=0; i<n; i++){
for(j=i+1; j<n; j++){
if(str[i]>str[j]){
temp = str[j];
str[j]=str[i];
str[i]=temp;
}
}
}
for(i=0; i<n; i++) printf("%c",str[i]);
printf("%s", str);
}
Related
I'm learning C and I've a problem with this school homework.
I have to make function which get two strings from user as parameters. The function removes all spaces from the first string and returns the "cleaned" strings as the other parameter.
The main function ask three strings, uses function to remove spaces and prints "cleaned" strings.
My code doesn't work as it should? What goes wrong?
#include <stdio.h>
void removeSpaces(char *, char *);
int main(){
int i, j;
char string[101], strings[1][101];
for(i = 0; i <= 2; i++){
fgets(string, 100, stdin);
for(j = 0; string[j] != '\0'; j++){
strings[i][j] = string[j];
}
strings[i][j] = '\0';
removeSpaces(strings[i], strings[i]);
}
for(i = 0; i <= 0; i++){
for(j = 0; j <= 101; j++){
printf("%c", strings[i][j]);
}
}
}
void removeSpaces(char *string1, char *string2){
int i, j;
for(i = 0; string1[i] != '\0'; i++){
if(string1[i] != ' '){
string2[i] = string1[j];
j++;
}
}
string2[i] = '\0';
}
You have to be more careful when writing code. There are several things wrong:
In removeSpaces(), you never initialize j. So it can be anything.
You are also mixing up i and j inside removeSpaces(). i should only be used to index string1, and j only for string2.
strings[1][101] is only one string, not 3. But the first for-loop in main() runs 3 times.
You don't have to print strings character by character, just printf("%s", strings[i]) or fputs(strings[i], stdout).
I'm not sure why you used a two-dimensional array strings here. You only need two strings. Renaming the variables can also help you avoid getting confused. Consider:
#include <stdio.h>
static void removeSpaces(const char *input, char *output) {
int i, o;
for(i = 0, o = 0; input[i] != '\0'; i++) {
if(input[i] != ' ') {
output[o] = input[i];
o++;
}
}
output[o] = '\0';
}
int main() {
char input[100], output[100];
fgets(input, sizeof input, stdin);
removeSpaces(input, output);
fputs(output, stdout);
}
I have been trying to remove the repeated consecutive characters from a string using c language for an assignment.
The input is like: sheeeiiisccommminng
The output must be like: sheiscoming
But I am getting the output: sheiscomng
I am not able to find out what went wrong here, please give your valuable insights.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
char str[100];
int i, j, k, len;
printf("Enter any string: ");
fgets(str, 100, stdin);
len = strlen(str);
for (i = 0; i < len; i++) {
j = i + 1;
k = i + 2;
while (j < len) {
if (str[j] == str[i]) {
j++;
} else {
str[k] = str[j];
k++;
j++;
}
}
len = k;
}
printf("\nString after removing characters:");
for (i = 0; i < len; i++) {
printf("%c", str[i]);
}
}
You should update the length of the string with len = k; after the end of the for loop.
Note however that you should also set a null terminator at the new length when you shorten the string to make it a proper C string.
Here is a simpler version:
#include <stdio.h>
int main() {
char str[100];
int i, j;
printf("Enter any string: ");
if (fgets(str, sizeof str, stdin)) {
for (i = j = 0; str[i] != '\0'; i++) {
if (j == 0 || str[j - 1] != str[i]) {
str[j] = str[i];
j++;
}
}
str[j] = '\0';
printf("String after removing characters: %s\n", str);
}
return 0;
}
Not sure about your code but you could do something like
char str[]="sheeeeisssscommmiingg";
int i, j;
for(i=j=0; str[j]; i++)
{
str[i]=str[j];
for(j++; str[j]==str[i]; ++j);
}
str[i]=`\0`;
printf("\n%s", str);
After examining a character in the string via the outer loop, subsequent characters which are the same are skipped using the inner for loop.
The original string is overwritten.
At the end, the nul terminator is added to the end of the new string.
Also consider reading this.
Output in this case is:
sheiscoming
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;
}
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;
}
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 ;
}
}