my program has two separate functions it excludes non-prime positions and then reserve the output from this. Except the issue I'm having is that at present it is not working how I want it to in the sense that the first function excludes the non prime places and then the second function uses the original input and reserves that instead of the output from function one. I'm new to C so please go easy on me.
#include <stdio.h>
#include <string.h>
void reverse(char[], long, long);
int main()
{
char str[50];
int i, j, k, cnt = 0;
long size;
printf("Enter: ");
scanf("%s", str);
size = strlen(str);
reverse(str, 0, size - 1);
printf(str);
return 0;
}
void reverse(char str[], long index, long size)
{
char temp;
temp = str[index];
str[index] = str[size - index];
str[size - index] = temp;
if (index == size / 2)
{
return;
}
reverse(str, index + 1, size);
}
Sorry for being so vague, a sample output from an input of 1234567 would be 2357 then this output reversed into 7532.
Here is what your code does (as it is written right now):
Input a string from console
Print out every character that is in a "prime position" (2, 3, 5, 7, etc) without modifying the string
Reverse the original, unmodified string
print out the reversed string
It sounds to me that what you are looking for is the following:
When you "exclude characters from a string" you create a new string that you populate with the characters from the input string that are in non-prime positions. Than you use that modified string as a parameter into the reverse() function.
I have no doubt that if you understand the above paragraph you'd have no problem fixing your code.
Here are the steps to achieve what you need:
input string into str (as you currently do)
introduce a new string str2 of the same size 50 as the original string
in your loop copy every character from str into str2 that is not in a "prime position"
call reverse() providing it the str2 as a parameter, not the (current) str
Related
EXAMPLE:
If I have this string/array: "123 45 6" (The numbers are separated by at least one space), how can I separate the numbers so I can use the numbers 123,45 and 6 separately?
I have know idea how to do it.
Thanks for helping!
Try strtol() (prototype in <stdlib.h>)
char data[] = "123 45 6";
char *p = data;
while (*p) {
long k = strtol(p, &p, 10);
/* add error checking */
printf("%ld\n", k);
}
Though I find the strtol-approach of png the most elegant way, let me also propose an approach utilising the "%n"-feature of scanf. This feature returns the number of characters scanned so far and can be used for pointing to the next portion to read in:
int main() {
const char *data = "123 45 6 ";
while (data && *data) {
int value=0;
int index=0;
if (sscanf(data,"%d%n",&value,&index) != 1)
break;
printf("%d\n", value);
data+=index;
}
}
You have to create a function which will split your string in a double array of strings, using spaces as a delimiter.
The prototype of this function would be for example :
char **StrSplit(char *str, char c);
Then you would be able to call it in your code with str as the string you want to take the numbers from, and c as the space character (or any character used as a delimiter).
It would return a double array of strings containing in each entry a string for each number.
Then you would be able to convert each entry (containing a string of numbers) as an integer using the function atoi on it.
I'm trying to do a simple parsing of text with a C program. A function I have written is supposed to check the buffer that has a line of text saved into it and see if this line contains a particular word at BOL.
The input arguments are:
size: the sizeof(word), calculated before the function is called.
buf: the buffer containing a line from the text being parsed.
word: the word that the function looks for at BOL.
The code is as follows:
#include <stdio.h>
#include <string.h>
int strchk(int size, const char buf[1024], char *word) {
char a[size];
int i;
for (i = 0; i < size - 1; i++) {
a[i] = buf[i];
}
if (strcmp(a, word) == 0)
return 1;
else
return 0;
}
The problem is that for some reason, a word is not being recognized. Previous words have been correctly identified by the same function. Below are two contexts wherein the function is being called, the first one results in a correct identification, the second does not, while the text contains both words at the start of different lines within the text.
char c[] = "|conventional_long_name";
if (strchk(sizeof(c), buf, c)) {
fputs(" conventional_long_name: \"", stdout);
getdata(buf, c, sizeof(c));
}
char d[] = "|official_languages";
if (strchk(sizeof(d), buf, d)) {
fputs(" religion: \"", stdout);
getdata(buf, d, sizeof(d));
}
When I check string a in the strchk() function for size first, it gives me a size of 20, but if I make it print out the string it tells me it is in fact |official_languagesfici. When you count the number of characters it's just as long as the previously mentioned |conventional_long_name, which would suggest some parameter from that function call is at play in the next function call, I just can't figure out where I have made the mistake. Any help would be greatly appreciated.
You need to set the null terminator of the a array in the function strchk.
Do it using
a[size - 1] = '\0';
after the for-loop.
Notes:
since you don't modify the string word in the function strchk, declare the parameter const. const-correctness is important!
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.
As simple as that. I'm on C++ btw. I've read the cplusplus.com's cstdlib library functions, but I can't find a simple function for this.
I know the length of the char, I only need to erase last three characters from it. I can use C++ string, but this is for handling files, which uses char*, and I don't want to do conversions from string to C char.
If you don't need to copy the string somewhere else and can change it
/* make sure strlen(name) >= 3 */
namelen = strlen(name); /* possibly you've saved the length previously */
name[namelen - 3] = 0;
If you need to copy it (because it's a string literal or you want to keep the original around)
/* make sure strlen(name) >= 3 */
namelen = strlen(name); /* possibly you've saved the length previously */
strncpy(copy, name, namelen - 3);
/* add a final null terminator */
copy[namelen - 3] = 0;
I think some of your post was lost in translation.
To truncate a string in C, you can simply insert a terminating null character in the desired position. All of the standard functions will then treat the string as having the new length.
#include <stdio.h>
#include <string.h>
int main(void)
{
char string[] = "one one two three five eight thirteen twenty-one";
printf("%s\n", string);
string[strlen(string) - 3] = '\0';
printf("%s\n", string);
return 0;
}
If you know the length of the string you can use pointer arithmetic to get a string with the last three characters:
const char* mystring = "abc123";
const int len = 6;
const char* substring = mystring + len - 3;
Please note that substring points to the same memory as mystring and is only valid as long as mystring is valid and left unchanged. The reason that this works is that a c string doesn't have any special markers at the beginning, only the NULL termination at the end.
I interpreted your question as wanting the last three characters, getting rid of the start, as opposed to how David Heffernan read it, one of us is obviously wrong.
bool TakeOutLastThreeChars(char* src, int len) {
if (len < 3) return false;
memset(src + len - 3, 0, 3);
return true;
}
I assume mutating the string memory is safe since you did say erase the last three characters. I'm just overwriting the last three characters with "NULL" or 0.
It might help to understand how C char* "strings" work:
You start reading them from the char that the char* points to until you hit a \0 char (or simply 0).
So if I have
char* str = "theFile.nam";
then str+3 represents the string File.nam.
But you want to remove the last three characters, so you want something like:
char str2[9];
strncpy (str2,str,8); // now str2 contains "theFile.#" where # is some character you don't know about
str2[8]='\0'; // now str2 contains "theFile.\0" and is a proper char* string.
How can one compare a string from the middle (or some other point but not the start) to another string?
like i have a string
str1[]="I am genius";
now if i want to find a word in it how should i compare it with the word? for example the word is am.
Here is what i did.Its a bit stupid but works perfectly :D
#include<stdio.h>
#include<string.h>
void print( char string[]);
int main()
{
int i;
char string1[20];
printf("Enter a string:");
gets(string1);
print(string1);
return 0;
getch();
}
void print(char string[])
{
int i,word=1,sum=0,x;
for(i=0; ;i++)
{
sum++;
if(string[i]==' ')
{
printf("Word#%d:%d\n",word,sum-1);
sum=0;
word++;
}/* if ends */
if(string[i]=='\0')
{ // program sai kaam karnay k liye ye code yahan bhi paste hona chahyey
printf("Word#%d:%d\n",word,sum-1);
sum=0;
word++;
break;
}
}/* for ends*/
}
Use strncmp():
strncmp( whereToFind + offsetToStartAt, patternToFind, patternLength );
If you wish to find a substring in a string, use the function strstr():
char *p = strstr(str1, "am");
if (p != NULL)
{
// p now points to start of substring
printf("found substring\n");
}
else
{
printf("substring not found\n");
}
If you want to compare the remainder of string s1 starting at index i1 to the remainder of string s2 starting at i2, it's very easy:
result = strcmp(s1+i1, s2+i2);
If you want to see if the substring of s1 beginning at i1 matches the string s2, try:
result = strcmp(s1+i1, s2);
or:
result = strncmp(s1+i1, s2, strlen(s2));
depending on whether you want the whole remainder of s1 to match or just the portion equal in length to s2 to match (i.e whether s1 contains s2 as a substring beginning at position i1.
If you want to search for a substring, use strstr.
Since this is homework I am assuming you can't use standard functions, so I can think of two solutions:
Split all of the words into a link
list, then just compare each string
until you find your word.
Just use a for loop, start at the
beginning, and you can use [] to
help jump through the string, so
instr[3] would be the fourth
character, as the index is
zero-based. Then you just see if you are at your word yet.
There are optimizations you can do with (2), but I am not trying to do your homework for you. :)
One option you be to use
size_t strspn( char *s1, const char *s2) /* from #include <string.h> */
*returns the length of the longest substring of s1 that begins at the start of s1 and consists only of the characters found in s2.
If it returns ZERO than there is no substring.
You can use parse the string into words and store them in new char arrays/pointers.
Or
Suppose the string you want to find is "am" stored in ptr *str2.
You start comparison using the index[] from str1 till you find a matching char for index 0 from str2
Once you find a match increment both pointers till you reach end of str2 to compare entire string.
If there is no match then continue to find char at index 0 in str2 in str1 from the place where you entered step 2.
Alternatively
You have to use a two dimensinal array.
char str[3][10] = { "i","am","2-darray"};
Here str[1] will contain "am". Thats assuming you want to get indvidual words of a string.
Edit: Removed the point diverting from OP