I've been trying to solve this for hours. Including research, but no go. Basically, we have to create function with :
int reverseSentence(char** sentence, char ** newsentance, int maxWords){
Where it returns the number of words in a sentence.
Here's more information:
You must maintain sentence capitalization, meaning if the sentence was capitalized, keep the
capital. If a word was capitalized, such as a name, retain the capital
The parameter sentence is a reference to a character array with the sentence to
reverse and should not be directly modified by your function. Each word is an array
entry in sentence.
The parameter newsentance is a reference to a character array to hold the new
sentence.
The parameter maxWords is the maximum size of the character array.
Return the number of words in the sentence
Do not copy the strings to temporary storage and replace them in the sentence. Move
the pointers.
ex: “To be, or not to be: that is the question.” becomes ”Question the is that be: to not or be, to.
Now, the problem I have is, currently my code works. But I can't seem to think of a way to capitalize something without getting an error. (Since we can't make a new storage).
What I have here is basically part of my code:
char ** fptr = sentence; //front sentence
char ** lptr = sentence; //last sentence
char ** nptr = newsentance;//front of new sentance
if( isupper(**fptr)){ //if the first letter of the first word is capital set flag
capflag = 1;
}
// find last word before null sentence and also calculate size
while(**(++lptr))
++size;
--lptr;
if(capflag){
*nptr = *lptr;
**nptr = toupper(**lptr); //error here
}
Also, I had to assume that the last "word" in sentence is "" or I can't find a way to calculate the size of the sentence. I hope someone can help me out.
I used this to test:
char ** test = malloc(1000);
*test = "To ";
*(test+1) = "be ";
*(test+2) = "or ";
*(test+3) = "not ";
*(test+4) = "to ";
*(test+5) = "be ";
*(test+6) = "";
char ** ztest = malloc(1000);
int rs = reverseSentence(test, ztest, 1000 );
Your code tries to modify a string literal, which is undefined behavior (you cannot do "ABC"[1] = 48; some implementations put string literals to readonly memory).
Try allocating space using malloc for each individual string and copy data from each string literal using memcpy.
The code below gives me the output:
To be or not to be; that is the question.
Number of words: 10
To be or not to be; that is the question.
question. the is that be; to not or be To
It only shuffles (copies of) pointers around; it does not attempt to modify the capitalization of words. If was going to do that, it would have to work harder, allocating copies of the leading word in the original sentence (but how would you tell whether that was a name or not?) and the last word. Suppose the sentence was "London hosted the 2012 Olympics"; when reversed, you don't want to case-convert the L of London because it is a name that happens to start the sentence (and you don't need to case-convert the O of Olympics either).
You could legitimately decide that the full stop (period) at the end of the sentence should not be included in the data (so my "question." should be replaced by "question"), and then have the sentence printing code add the full stop at the end; it is a trivial modification.
#include <stdio.h>
int reverse_sentence(char **fwd_order, char **rev_order, int max_words)
{
char **end = fwd_order;
int num_words = 0;
for (end = fwd_order; *end != 0 && num_words < max_words; end++)
num_words++;
for (int i = 0; i < num_words; i++)
*rev_order++ = *--end;
*rev_order = 0;
return num_words;
}
static void print_sentence(char **words)
{
const char *pad = "";
while (*words)
{
printf("%s%s", pad, *words++);
pad = " ";
}
putchar('\n');
}
int main(void)
{
char *sentence[] =
{ "To", "be", "or", "not", "to", "be;", "that", "is", "the", "question.", 0 };
enum { NUM_WORDS = sizeof(sentence) / sizeof(sentence[0]) };
char *reversed[NUM_WORDS];
int num_words;
print_sentence(sentence);
num_words = reverse_sentence(sentence, reversed, NUM_WORDS);
printf("Number of words: %d\n", num_words);
print_sentence(sentence);
print_sentence(reversed);
return(0);
}
ex: “To be, or not to be: that is the question.” becomes ”Question the is that be: to not or be, to.
Is this part of the specification or is it your interpretation? If the latter, you should verify whether your interpretation is correct or whether you are to simply reverse the order of the words, which is easily achievable. Do you even know if you are required to handle punctuation? Your code doesn't, and your test doesn't match your example.
First rule of software engineering: nail down the requirements.
Related
So I am working away on the 'less comfortable' version of the initials problem in CS50, and after beginning with very verbose code I've managed to whittle it down to this:
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int c = 0;
int main(void)
{
string name = get_string();
int n = strlen(name);
char initials[10];
// first letter is always going to be the first initial
initials[0] = name[0];
// count through letters looking for spaces + add the first letter after a
// space to the initials array
for (int j = 0; j < n; j++)
{
if (name[j] == 32)
{
c += 1;
initials[c] += name[j+1];
}
}
// print out initials
for (int k = 0; k <= c; k++)
{
printf("%c", toupper(initials[k]));
}
printf("\n");
}
As it stands like that it passes, but I feel like I am copping out a little cos I just pick [10] out of the air for the initial array size which I know isn't good practice. To make it a little 'better' I've tried to run a 'for' loop to iterate through the name string and add up the number of spaces. I then want to make the array [spaces + 1] as if there are 2 spaces then there will be 3 initials. The code I am trying for that is:
string name = get_string();
int n = strlen(name);
for (int i = 0; i < n; i++)
{
if (name[i] == 32)
{
spaces +=1;
}
}
The thought is that I then make 'char initials[spaces + 1]' on the next line, but even before I can do that, compiling my code with just this 'for' loop returns a fail when I upload it for checking (although it compiles no problem). Even if I don't use any of the 'for' loops output the mere fact it is there gives me this error.
Where am I going wrong?
Any help on this would be much appreciated.
Thanks!
First of all, keep in mind that execution speed is most often more valuable than memory use. If you first go look for spaces and after that allocate memory, you have to iterate through the array twice. This is an optimization of memory use at the cost of execution speed. So it might make more sense to just allocate a "large enough" array of lets say 100 characters and keep the code that you have.
I then want to make the array [spaces + 1] as if there are 2 spaces then there will be 3 initials
Keep in mind that C strings are null terminated, so you need to allocate room for the null terminator too, spaces + 1 + 1.
compiling my code with just this 'for' loop returns a fail when I upload it for checking (although it compiles no problem). Even if I don't use any of the 'for' loops output the mere fact it is there gives me this error.
What error? Does it compile or does it not compile, your text is contradicting.
Make sure you initialize spaces to zero.
As a side note, never use "magic numbers" in C code. if (name[i] == 32), 32 is gibberish to anyone who can't cite the ASCII table by memory. In addition, it is non-portable to systems with other symbol tables that might not have the same index numbers. Instead write:
if (name[i] == ' ')
In my opinion, a good approach to cater for such situations is the one the library function snprintf uses: It requires you to pass in the string to fill and the size of that string. In ensures that the string isn't overwritten and that the string is zero-terminated.
The function returns the length of the characters written to the string if the had the string been large enough. You can now do one of two things: Guess a reasonable buffer size and accept that the string will be cut short occasionally. Or call the function with a zero length, use the return value to allocate a char buffer and then fill it with a second call.
Applying this approach to your initials problem:
int initials(char *ini, int max, const char *str)
{
int prev = ' '; // pretend there's a space before the string
int n = 0; // actual number of initials
while (*str) {
if (prev == ' ' && *str != ' ') {
if (n + 1 < max) ini[n] = *str;
n++;
}
prev = *str++;
}
if (n < max) {
ini[n] = '\0';
} else if (max > 0) {
ini[max] = '\0';
}
return n;
}
You can then either use the fixed-size bufer approach:
char *name = "Theodore Quick Brown Fox";
char ini[4];
initials(ini, sizeof(ini), name);
puts(ini); // prints "TQB", "F" is truncated
Or the two-step dynamic-size approach:
char *name = "Theodore Quick Brown Fox";
int n;
n = initials(NULL, 0, name);
char ini[n + 1];
initials(ini, sizeof(ini), name);
puts(ini); // prints "TQBF"
(Note that this implementation of initals will ignore multiple spaces and spaces at the end or at the beginning of the string. Your look-one-ahead function will insert spaces in these cases.)
You know your initials array can't be any bigger than the name itself; at most, it can't be more than half as big (every other character is a space). So use that as your size. The easiest way to do that is to use a variable-length array:
size_t n = strlen( name ); // strlen returns a size_t type, not int
char initials[n/2+1]; // n/2+1 is not a *constant expression*, so this is
// a variable-length array.
memset( initials, 0, n + 1 ); // since initials is a VLA, we can't use an initializer
// in the declaration.
The only problem is that VLA support may be iffy - VLAs were introduced in C99, but made optional in C2011.
Alternately, you can use a dynamically-allocated buffer:
#include <stdlib.h>
...
size_t n = strlen( name );
char *initials = calloc( n/2+1, sizeof *initials ); // calloc initializes memory to 0
/**
* code to find and display initials
*/
free( initials ); // release memory before you exit your program.
Although, if all you have to do is display the initials, there's really no reason to store them - just print them as you find them.
Like others have suggested, use the character constant ' ' instead of the ASCII code 32 for comparing against a space:
if ( name[j] == ' ' )
or use the isspace library function (which will return true for spaces, tabs, newlines, etc.):
#include <ctype.h>
...
if ( isspace( name[j] ) )
I keep receiving "Segmentation fault (core dumped)".
How can I swap the first letter of a given word that the user inputs to the end of the word and then add an "ay".
For example:
input "Code"
output "odecay"
#include<stdio.h>
#include<string.h>
int main()
{
char pig[100],p[10],i[100];
int j,length;
printf("What word would you like to change into pig latin");
scanf("%s",pig);
length=strlen(pig);
strcat(p,pig[0]);
for(j=0;j<length;j++)
{
pig[j]=pig[j+1];
}
strcat(pig,p);
strcat(pig,"ay");
printf("%s",pig);
return 0;
}
How can I swap the first letter of a given word that the user inputs to the end of the word and then add an "ay"
Save the first character ("letter")
char c = pig[0];
Move the rest of pig one char to the beginning
memmove(pig, pig + 1, strlen(pig) - 1);
alternativly use this statement
memmove(&pig[0], &pig[1], strlen(pig) - 1);
(Note that memcpy() won't work here as source and destiantion overlap.)
Replace the "old" last character with the "old", stored first character
pig[strlen(pig) - 1] = c;
Append "ay"
strcat(pig, "ay");
Print the result:
printf("%s\n", pig);
There is no need for a second "string", char-array.
Assuming pig is large enough, that is one char larger then the data to be scanned in from the user, one can even ommit the use of the intermediate character `c, as per my sketch above.
Initialise pig to all 0s
char pig[100] = "";
Scan in data
scanf("%98s", pig); /* Add tests for failure reading as needed. */
Append the first character of the input, that is copy it to the end of pig
pig[strlen(pig)] = pig[0];
Move all of pig one character to the beginning
memmove(pig, pig + 1, strlen(pig) - 1);
Print the result:
printf("%s\n", pig);
This code runs but there is a slight problem with your algorithm. Since this is probably homework I'll let you figure that part out.
#include <stdio.h>
#include <string.h>
int main()
{
// These should be initialized before use.
char pig[100] = "",
char p[10] = "";
printf("What word would you like to change into Pig Latin: ");
scanf("%s", pig);
unsigned long length = strlen(pig); // strlen returns an unsigned long
strcat(p, &pig[0]); // This needs a pointer to char
for(int j = 0; j < length; j++)
{
pig[j] = pig[j + 1];
}
strcat(pig, p);
strcat(pig, "ay");
printf("%s", pig);
return 0;
}
Input:
Code
Output:
odeCodeay
As I said, the algorithm is not quite right but now that the code runs you should be able to fix it pretty quick. Also, since you are new to programming notice some of the code formatting which makes it more readable.
EDIT
Since others have already mentioned it, changing the line strcat(p, &pig[0]); to strncat(p, pig, 1); will produce the desired output and still use your original algorithm.
strcat(p,pig[0]); // segmentation fault may happen in this line.
char *strcat(char *dest, const char *src) // takes two string but you are passing pig[0] in the second argument which is char
You can use char *strncat(char *dest, const char *src, size_t n)
Thus the proper way to concat a char to a string would be
strncat(p,&pig[0],1); // where 1 is passed in the third argument
//so that it reads only 1 char i.e. pig[0] and ignore next characters
// otherwise the whole pig string will be concatenated.
This is in Ansi C. I am given a string. I am supposed to create a method that returns an array of character pointers that point to the beginning of each word of said string. I am not allowed to use Malloc, but instead told that the maximum length of input will be 80.
Also, before anyone flames me for not searching the forum, I can't use strtok :(
char input[80] = "hello world, please tokenize this string"
and the output of the method should have 6 elements;
output[0] points to the "h",
output[1] points to the "w",
and so on.
How should I write the method?
Also, I need a similar method to handle input from a file with maximum of 110 lines.
Pseudocode:
boolean isInWord = false
while (*ptr != NUL character) {
if (!isInWord and isWordCharacter(*ptr)) {
isInWord = true
save ptr
} else if (isInWord and !isWordCharacter(*ptr)) {
isInWord = false
}
increment ptr
}
isWordCharacter checks whether the character is part of the word or not. Depending on your definition, it can be only alphabet character (recognize part-time as 2 words), or it may include - (recognize part-time as one word).
Because it's homework here's a part of what you might need:
char* readPtr = input;
char* wordPtr = input;
int wordCount = 0;
while (*readPtr++ != ' ');
/* Here we have a word from wordPtr to readPtr-1 */
output[wordCount++] = /* something... :) */
You'll need that in a loop, and must consider how to move onto the next word, and check for end of input.
i am writing a C program and one of the issues i have is to extract a word between two words as below.
ac_auto_lvalue[] =
"ONLY / GROUP: OTHERS EXAMPLE /-----------------------------";
I need to extract the word between "Group:" and the "/", the two words (Group:" & "/") will always be there but the words in between can change and in some cases there might be nothing... ( in the above example output would be "OTHERS EXAMPLE"
can anyone help me with a C snippet for the above?
Take a look at the strstr function. It lets you find a pointer to the first occurrence of a specific string (say, "Group:") inside another string. Once you have two pointers (to the beginning and to the end of your string) you can allocate enough memory using malloc (don't forget the terminating zero '\0'), use memcpy to copy the characters, and finally zero-terminate your string.
int main() {
char ac_auto_lvalue[] = "ONLY / GROUP: OTHERS EXAMPLE /-----------------------------";
// Adding 7 to compensate for the length of "GROUP: "
const char *p1 = strstr(ac_auto_lvalue, "GROUP: ")+7;
const char *p2 = strstr(p1, " /");
size_t len = p2-p1;
char *res = (char*)malloc(sizeof(char)*(len+1));
strncpy(res, p1, len);
res[len] = '\0';
printf("'%s'\n", res);
return 0;
}
Use strstr for Group, increment that pointer by the length of Group (6).
I am processing an input string, which consists of a process name, followed by an arbitrary amount of arguments.
I need the process name , along with all of the arguments, in one string.
I thought I could use strcat in a loop, so that it cycles through all of the args and each time appends the arg to the string, but I am having problems with getting a string that in empty to begin the loop.
Can anyone help me out with some basic code?
Thanks.
EDIT:
I'm posting my code for clarity. Mike's post is closest to what I have now:
char * temp;
strcpy(temp,"");
for (i = 4; i < argc-1; i++) // last arg is null, so we need argc-1
{
strcat(temp,argv[i]);
strcat(temp," ");
}
ignore the 4 in my for loop for the moment (magic number, i know.)
I am getting a segfault with this code. Is it because of my string assignment? I assume that is the case and hence I asked the question of how i could combine the strings.
Let's say your input strings are in an array of char pointers, suggestively called argv, of length argc.
We first need to determine how much space is needed for the output:
int length = 0;
for (int i = 0; i < argc; ++i)
length += strlen(argv[i]);
Then we allocate it, adding an extra char for the '\0' terminator:
char *output = (char*)malloc(length + 1);
Finally, the concatenation:
char *dest = output;
for (int i = 0; i < argc; ++i) {
char *src = argv[i];
while (*src)
*dest++ = *src++;
}
*dest = '\0';
Note that I don't use strcat here. Reason is that this sets us up for a Schlemiel the Painter's algorithm: for each iteration, the entire output string would be scanned to find its end, resulting in quadratic running time.
Don't forget to free the output string when you're done:
free(output);
I'm a bit tired so I may be overlooking something here. A better solution, using standard library functions, is welcome. It would be convenient if strcat returned a pointer to the terminator byte in dest, but alas.
You want an empty C string? Is this what you are looking for: char p[] = "";?
UPDATE
After you posted some code it is clear that you have forgotten to allocate the buffer temp. Simply run around the arguments first, counting up the length required (using strlen), and then allocate temp. Don't forget space for the zero terminator!
You could provide the "arbitrary amount of arguments" as one argument, ie an array/list, then do this pseudocode:
str = "";
i = 0;
while i < length of input
{
str = strcat ( str , input[i]);
i++;
}
#include<stdio.h>
#include<stdarg.h>
int main(int argc, char** argv) {
// the main parameters are the same situation you described
// calling this program with main.exe asdf 123 fdsa, the program prints out: asdf123fdsa
int lengths[argc];
int sum =0;
int i;
for(i=1; i<argc; i++) { // starting with 1 because first arg is program-path
int len = strlen(argv[i]);
lengths[i] = len;
sum+=len;
}
char* all = malloc(sum+1);
char* writer = all;
for(i=1; i<argc; i++) {
memcpy(writer, argv[i], lengths[i]);
writer+=lengths[i];
}
*writer = '\0';
printf("%s\n", all);
system("pause");
return 0;
}
A string in C is represented by an array of characters that is terminated by an "null" character, '\0' which has the value 0. This lets all string functions know where the end of a string is. Here's an exploration of different ways to declare an empty string, and what they mean.
The usual way of getting an empty string would be
char* emptyString = "";
However, emptyString now points to a string literal, which cannot be modified. If you then want to concatenate to an empty string in your loop, you have to declare it as an array when you initialize.
char buffer[] = "";
This gives you an array of size one. I.e. buffer[0] is 0. But you want an array to concatenate to- it has to be large enough to accomodate the strings. So if you have a string buffer of certain size, you can initialize it to be empty like so:
char buffer[256] = "";
The string at buffer is now "an empty string". What it contains, is buffer[0] is 0 and the rest of the entries of the buffer might be garbage, but those will be filled once you concatenate your other strings.
Unfortunately, the problem with C, is you can never have an "infinite" string, where you are safe to keep concatenating to, you have to know it's definite size from the start. If your array of arguments are also strings, you can find their length using strlen. This gives you the length of a string, without the null character. Once you know the lengths of all your sub-strings, you will now know how long your final buffer will be.
int totalSize; // assume this holds the size of your final concatenated string
// Allocate enough memory for the string. the +1 is for the null terminator
char* buffer = malloc(sizeof(char) * (totalSize + 1));
buffer[0] = 0; // The string is now seen as empty.
After this, you are free to concatenate your strings using strcat.