i have a string that is made out of a few sentences.
for example:
hello world bye bye
now, i need to make this sentence into a coulmn of words:
hello
world
bye
bye
i have this idea going on, but i dont know how to write it correctly, so i was hopiny ypu guys could help me out.
this is what i have so far:
int len=0, k=0, stopatspace=0;
char temptext[100][15]={0};
char line[300]={0};
len=strlen(line);
printf("len is: %d", len);
for(k=0; k<len; k++)
{
if (k == ' ')
{
// i dont know what to write here in order to make it a cloumn
}
}
basiclly, my idea is to run on all the length of my line and when i reach a space i want it to enter (to go one line down so that it will look like a coulmn)
Suppose line is the char array that contains hello world bye bye and text is declared as
char text[100][15]; //I used 100 and 15 because your example contains it
and you want each word to be copied into each row of text. Then,use strtok() function with " "(space) as delimeter and place this in a loop that terminates when strtok() returns NULL to get each word. Copy each word to each row of text using strcpy() in the loop.
The code for this will look like this:
char text[100][15];
char line[]="hello world bye bye";
int i=0;
char *token=strtok(line," ");
while(token!=NULL)
{
strcpy(text[i],token);
i++;
token=strtok(NULL," ");
}
Now, to print it,you can use
for(int j=0;j<i;j++)
printf("text[%d]=%s",j,text[j]);
Another method would be to manually copy each character until a space is seen.
int len=strlen(line);
int i=0;
int k=0;
for(int j=0;j<len+1;j++)
{
if(line[j]==' ')
{
text[i][k]='\0';
i++;
k=0;
}
else
{
text[i][k]=line[j];
k++;
}
}
Note that the above code does not prevent buffer overflows. You can print each word using
for(int j=0;j<i+1;j++)
printf("text[%d]=%s",j,text[j]);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string[100];
fgets(string, 100, stdin);
string[strlen(string)-1] = 0;
// create an array of pointers
char **string_array = (char**)malloc(sizeof(char*));
int i = 0, array_size;
// tokenize input
char *token = strtok(string, " ");
while(token!=NULL) {
// dynamically increase the array during run time
string_array = (char**)realloc(string_array, (i+1)*sizeof(char**));
// create the string as you would do when there is only one string
string_array[i] = (char*)malloc(strlen(token)+1);
strcpy(string_array[i], token);
token = strtok(NULL, " ");
i++;
}
array_size = i;
for(i=0; i<array_size; i++) {
printf("%s\n", string_array[i]);
}
return 0;
}
Basically you create an array of pointers and you allot memory for the strings one by one as you would do when there is only one string.
(if number of token is unknown, use realloc to increase the size of pointer to pointers.)
#include <stdio.h>
#include <ctype.h>
int main(void){
char line[300] = "hello world bye bye\n";
char temptext[100][15]={0};
int i=0, j, k=0;
while(line[k]){
if(isspace(line[k])){
++k;//skip space to word
continue;
}
for(j=0; j < 15-1 && line[k] && !isspace(line[k]); ++k, ++j)
temptext[i][j] = line[k];
if(j && ++i == 100)
break;
}
for(j=0; j<i; ++j)
puts(temptext[j]);
return 0;
}
#include<stdio.h>
#define NEWLINE printf("\n")
int main(void)
{
char string[]="hello world bye bye";
int index=0;
while(string[index])
{
if(string[index]==32)
{
NEWLINE;
index++;
}
else
{
printf("%c",string[index]);
index++;
}
}
NEWLINE;
}
// Whenever i encountered with a space, i am printing a new line on the screen. Here 32 is the ASCII value for space
Related
I have an assignment to write a program in C that functions similarly to the bash sed 's/oldstring/newstring/g' but only using stdio.h and string.h. We cannot use malloc s we have not yet covered it in class. The program has to continue to take user input until the user enters ^D. We're using GCC so I have it set up to use variable length arrays and I've managed to get the program to find and replace a single instance of oldstring in the user input. However, on occasion the program will output some garbage characters and I am not sure why. I assume it is a memory allocation error or the program is reading past where I want it to read. The code is below:
#include <stdio.h>
#include <string.h>
int isMatch(char * os, char * us){
int i;
char temp[strlen(os)];
for(i=0; i<strlen(us); i++){
int k=0;
for(int j=i; j<i+strlen(os); j++){
temp[k]=us[j];
k++;
}
if(strcmp(temp, os)==0){
return 1;
}
else{
return 0;
}
}
}
void replace(char * os, char * us, char * ns, int loc){
char out[strlen(us) - (strlen(os) - strlen(ns))];
int i;
for(i=0; i<loc; i++){
out[i]=us[i];
}
int k=0;
for(i=loc; i<loc+strlen(ns); i++){
out[i]=ns[k];
k++;
}
k=0;
for(i=loc+strlen(ns); i<strlen(us)-(strlen(os)-strlen(ns)); i++){
out[i]=us[loc+strlen(os)+k];
k++;
}
printf("%s\n", out);
}
int main(int argc, char * argv[]){
char input[100];
int i;
char c;
int match;
while(1){
if(scanf("%c", &c)==EOF){
break;
}
if((input[0]=c) != '\n'){
for(i=1; i<100; i++){
scanf("%c", &input[i]);
if(input[i]=='\n'){
break;
}
}
}
for(i=0; i<100; i++){
match = isMatch(argv[1], &input[i]);
if(match == 1){
replace(argv[1], input, argv[2], i);
}
if(input[i]=='\n'){
break;
}
}
}
}
I call the program with ./a.out aa b for example.
I then enter helaalo and the program spits out helblo which is correct. I then enter libraary and the program outputs librbry followed by some random characters on new lines. I then enter caar and the program outputs cbr followed by even more random letters on new lines. A screenshot of this behavior is included.
Since you can't use malloc, you can force to add terminating \0 for the end of input string and end of out string,
// input
for(i=1; i<100; i++){
scanf("%c", &input[i]);
if(input[i]=='\n'){
input[i] = '\0'; // add terminating \0 for input
break;
}
}
// out
for(i=loc+strlen(ns); i<strlen(us)-(strlen(os)-strlen(ns)); i++){
out[i]=us[loc+strlen(os)+k];
k++;
}
int len = strlen(us)-(strlen(os)-strlen(ns));
out[len] = '\0'; // for out termiante \0
printf("%s\n", out);
The problem is coming from your the way you are filling your input buffer. You don't add a \0 at the end of the string.
There is also an other "problem", when you declare you array out if you want a dynamic size you need to use a malloc. how you are declaring it will not have a dynamic size , the size of the array will be calculated at compilation time. Just to keep it in mind.
I found this c programming code on https://www.includehelp.com/c-programs/c-program-to-split-string-by-space-into-words.aspx
/*C program to split string by space into words.*/
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
char splitStrings[10][10]; //can store 10 words of 10 characters
int i,j,cnt;
printf("Enter a string: ");
gets(str);
j=0; cnt=0;
for(i=0;i<=(strlen(str));i++)
{
// if space or NULL found, assign NULL into splitStrings[cnt]
if(str[i]==' '||str[i]=='\0')
{
splitStrings[cnt][j]='\0';
cnt++; //for next word
j=0; //for next word, init index to 0
}
else
{
splitStrings[cnt][j]=str[i];
j++;
}
}
printf("\nOriginal String is: %s",str);
printf("\nStrings (words) after split by space:\n");
for(i=0;i < cnt;i++)
printf("%s\n",splitStrings[i]);
return 0;
}
I had run this code and I have entered the string for an example "The dog is sad" The output will be
The
Dog
Is
Sad
I was wondering if I could count the numbers of the characters after splitting the word; like for an example;
The 3
Dog 3
Is 3
Sad 3
I do not know how to achieve that desired output. Thank you
Your last printf could be:
printf("%s %d ",splitStrings[i], strlen(splitStrings[i]));
You already use strlen() in your first for loop.
Use this modified printf:
/*C program to split string by space into words.*/
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
char splitStrings[10][10]; //can store 10 words of 10 characters
int i,j,cnt;
printf("Enter a string: ");
gets(str);
j=0; cnt=0;
for(i=0;i<=(strlen(str));i++)
{
// if space or NULL found, assign NULL into splitStrings[cnt]
if(str[i]==' '||str[i]=='\0')
{
splitStrings[cnt][j]='\0';
cnt++; //for next word
j=0; //for next word, init index to 0
}
else
{
splitStrings[cnt][j]=str[i];
j++;
}
}
printf("\nOriginal String is: %s",str);
printf("\nStrings (words) after split by space:\n");
for(i=0;i < cnt;i++)
printf("%s %d ",splitStrings[i],strlen(splitStrings[i]));//modified
return 0;
}
I am trying to take a user inputted string and look at each code to see if it appears in another string of strings. So far my code works.
If the word is successfully found then the alpha representation is to be added to an array that will eventually be printed, but only if all codes were found.
I am having issues with what gets stored in my array that is going to be printed.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char *string;
typedef char *alpha;
int main(void)
{
string morse[4]={".-", "-...","----.", ".."};
string alpha[4]={"A", "B", "9", "I"};
char prntArr[50];
char *input;
char *hold;
input = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
int ret;
int x;
int w=0;
int z=0;
printf("please enter a string\n");
scanf("%[^\n]",input);
do{
if (input[i] !=' ')
{
hold[j] = input[i];
j++;
}
else
{
hold[j]='\0';
for (x=0;x<4;x++)
{
printf("value of x %d\n",x);
ret = strcmp(morse[x], hold);
if (ret==0)
{
printf("%s\n",alpha[x]);
prntArr[w]=*hold;
w++;
x=4;
}
else
{
ret=1;
printf("invalid Morse code!");
}
}
j = 0;
}
i++;
}while(input[i] !='\0');
for (z=0;z<50;z++)
{
printf("%c",prntArr[z]);
}
return 0;
free(input);
}
The problem you asked about is caused by the way prntArr is used in the program. It really should be an array of character pointers into the alpha array. Instead, it's manipulated as an array of characters into which the first character of each morse code element is stored. And when it's printed, the variable that tracks how much of the array is used is simply ignored.
Another problem is that your code uses spaces to break the codes but there won't necessarily be a space at the end of the line so a code might get missed. In the program below, I switched out scanf() for fgets() which leaves a newline character on the end of the input which we can use, like space, to indicate the end of a code.
Other problems: you print the invalid Morse code message at the wrong point in the code and you print it to stdout instead of stderr; you remember to free input but forget to free hold; you put code after return that never gets called.
Below is a rework of your code that addresses the above problems along with some style issues:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(void)
{
char *morse[] = {".-", "-...", "----.", ".."};
char *alpha[] = {"A" , "B" , "9" , "I" };
char *print_array[50];
int print_array_index = 0;
char hold[50];
int hold_index = 0;
char input[200];
int i = 0;
printf("please enter a string: ");
fgets(input, sizeof(input), stdin);
while (input[i] !='\0') {
if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';
bool found = false;
for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "invalid Morse code: %s\n", hold);
}
hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}
i++;
}
for (int x = 0; x < print_array_index; x++)
{
printf("%s ", print_array[x]);
}
printf("\n");
return 0;
}
SAMPLE RUNS
> ./a.out
please enter a string: ----. -... .- ..
9 B A I
>
> ./a.out
please enter a string: .- --- ..
invalid Morse code: ---
A I
>
I have written a code trying to split a long string to get simpler strings so that i could sort them out... When i break from the nested loop, does it break up to the first loop entirely??
My input is "&$(, My,na$me(is"
the output that i wanted is "My na me is"
How can i solve this??
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(){
char splitter[100];
char mystring[1000];
char newstring[1000][1000];
int i,j,z,k=0;
scanf("%s", splitter);
scanf("%s", mystring);
for (i=0; i<1000; i++){
for (j=k; j<1000; j++){
for (z=0; z<100; z++){
if (mystring[j]==splitter[z]){
k++;
break;
}
else
{
newstring[i][j]=mystring[j];
}
}
if (mystring[j]==splitter[z])
break;
}
}
for (i=0; i<10; i++){
printf("%s ", newstring[i]);
}
return 0;
}
First; C is not Python, you can't just use indent to denote blocks, you must use braces, i.e. { and }.
Second, no a break only breaks the closest-most loop its in, there's no way to break out of more than one level.
Third, you're looping over the strings as if they're always 100 characters long which they won't always be (for instance in your example they're not). This is wrong, you should use strlen() to figure out how long they are.
Fourth, you should check the return values of your scanf() calls, since it can fail.
Fifth, newstring is declared as an array of arrays, i.e. a gigantic one-megabyte 2D "square" of characters, which is clearly not how you're using it.
#include <stdio.h>
#include <string.h>
int main(){
char splitter[100];
char mystring[1000];
char *tokens[500];
char *token;
int i=0;
scanf("%99[^\n]%*c", splitter);
scanf("%999[^\n]", mystring);
token = strtok(mystring, splitter);
while(token){
if(i)
putchar(' ');
printf("%s", token);
tokens[i++] = token;
token = strtok(NULL, splitter);
}
putchar('\n');
return 0;
}
Though there are many mistakes in your code and I am unable to find out why are you doing those mistakes.For example I dint get why are you scaning two arrays and why are you using a two-D array.Another thing I would like to tell you is that scanf doesnt work when there is spaces in the string.According to your problem here is very simple solution.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(){
char splitter[100];
char mystring[1000];
char newstring[1000][1000];
int i,j,z,k=0;
gets(splitter);
for(i=0;i<strlen(splitter);++i){
if(((splitter[i])>=65 &&(splitter[i]<=90)) || ((splitter[i]>=97)&&(splitter[i] <=122)))
mystring[k++]=splitter[i];
else
mystring[k++]=' ';
}
printf("%s\n",mystring);
//scanf("%s", mystring);
return 0;
}
Check the below code:
int main()
{
int i=0,j=0,t,f=0;
char s[20];
char b[20];
printf("Enter the string\n");
scanf("%s",&s);
while(s[i] != '\0')
{
t = s[i];
if((t>=65 && t<=90) || (t>= 97 && t<=122))
{
b[j++] = s[i];
f = 1;
}
else
{
if(f)
b[j++] = ' ';
}
i++;
}
b[j] = '\0';
printf("%s\n",b);
return 0;
}
So after a few years of inactivity after studying at uni, I'm trying to build up my c experience with a simple string reverser.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
reverser();
return(0);
}
int reverser(){
printf("Please enter a String: ");
//return (0);
int len;
char input[10];
scanf("%s",&input);
int quit = strcmp(input,"quit");
if(quit == 0){
printf("%s\n","Program quitting");
return(0);
}
len = strlen(input);
printf("%i\n",len);
char reversed[len];
int count = 0;
while (count <= (len-1)){
//printf("%i\n",(len-count));
reversed[count] = input[(len-1)-count];
count++;
}
//printf("%s\n",input);
printf(reversed);
printf("\n");
reverser();
}
When I input "hello", you would expect "olleh" as the response, but I get "olleh:$a ca&#",
How do I just get the string input reversed and returned?
Bombalur
Add a '\0' at the end of the array. (as in, copy only chars until you reach '\0' - which is the point at array[strlen(array)], then when you're done, add a '\0' at the next character)
Strings are conventionally terminated by a zero byte. So it should be
char reversed[len+1];
And you should clear the last byte
reversed[len] = (char)0;
you forgot the \0 at the end of the string
This is because you are creating an array with size 10. When you take in some data into it (using scanf) and the array is not filled up completely, the printf from this array will give junk values in the memory. You should iterate for the length of the input by checking \n.
must have a size + 1 to string length so that you can have a \0 at the end of string that will solve your problem
The following is a (simple and minimal implementation of) string reverse program (obviously, error conditions, corner cases, blank spaces, wider character sets, etc has not been considered).
#include <stdio.h>
int strlen(char *s)
{
char *p = s;
while (*p)
p++;
return p - s;
}
char * strrev(char a[])
{
int i, j;
char temp;
for (i=0, j=strlen(a)-1 ; i<j ; i++, j--) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
int main()
{
char str[100];
printf("Enter string: ");
scanf("%s", str);
printf("The reverse is %s \n", strrev(str));
return 0;
}
Hope this helps!