Cut out section of a string with another string - c

I got this part of a C program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
char *mRNA = spleissen("AUAGUAAAAGCUCUGUUUAGGAGA", "GU", "AG");
printf("mRNA: %s\n", mRNA);
free(mRNA);
return 0;
}
I have to write the function spleissen which should work like this: it cuts out a string which goes from a GU to an AG and everything in between those two. So the program output is:
mRNA: AUACUCUGAGA
I don't really know how I can cut those parts out.
I am not allowed to use includes other than stdio, string and stdlib.

char *spleissen(const char *src, const char *start, const char *end){
size_t len = strlen(src);
char *s, *e, *ret, *work;
ret = work = malloc(len + 1);
strcpy(work, src);
len = strlen(end);
while(s = strstr(work, start)){
if((e = strstr(s, end))==NULL)
break;//delete upto last?
memmove(s, e + len, strlen(e+len)+1);
work = s;
}
return ret;
}

I think you can simply do this:
char *spleissen(char *array, char *G, char *A)
{
int l=strlen(array);
int i, j=0;
char returnstr[10010];
int b=0;
for(i=0; i<l; i++)
{
if(G[0]==array[i] && G[1]==array[i+1])
{
b=1, i++;
continue;
}
else if(A[0]==array[i] && A[1]==array[i+1] && b==1)
{
b=0, i++;
continue;
}
if(b==0)
{
returnstr[j]=array[i];
j++;
}
}
return returnstr;
}

Related

Getting jargon before actual data when printing char pointer

I'm writing a program that implements the Alberti Cipher, and when testing, the final print always gives a string of jargon before the actual encryption. Right now its printing \x80\x16G\xbf\xfe\x7fKHOORZRUOG, with KHOOR..... being the actual encryption. Any help appreciated :)
#include <stdio.h>
#include <stdlib.h>
int letterToNumber(char letter){
char str[2] = { letter };
int num = strtol( str, NULL, 36 ) - 10;
return num;
}
int getSize (const char * s) {
const char * t;
int size = 0;
for (t = s; *t != '\0'; t++) {
size++;
}
return size;
}
char numToChar(int numInp){
numInp=numInp+65;
char returnChar=(char)numInp;
return returnChar;
}
void encrypt_alberti(const char *message,const char *inner_ring, int initialShift,int periodicShift,int periodLength,char **result){
//sets initial shift
int numArray[25];
int count=0;
int shiftCount=0;
for(int i = 0; i < 26; ++i) {
numArray[i]=(i+initialShift)%26;
}
//encrypts each character and prints
int messageSize=getSize(message);
char encryptedMessage[messageSize];
for(int i=0; i<messageSize;i++){
count++;
if(periodicShift!=0){
if(count%periodicShift==0){
shiftCount++;
}
}
else{
periodLength=0;
}
char toBeEncrypted=message[i];
int charNumber=letterToNumber(toBeEncrypted);
int encryptedNum=numArray[(charNumber+(shiftCount*periodLength))%26];
char encryptedChar=numToChar(encryptedNum);
strncat(encryptedMessage, &encryptedChar, 1);
}
char* p1=malloc(sizeof(encryptedMessage));
strcpy(p1,encryptedMessage);
*result=p1;
}
void main(void) {
const char *example_message = "HELLOWORLD";
const char *example_inner = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *encrypted_message = NULL;
encrypt_alberti(example_message, example_inner, 3, 0, 1, &encrypted_message);
printf("message is %s\n", encrypted_message);
printf("-----------------");
free(encrypted_message);
}
}

How to merge arrays passed to a function with variable parameters

Ive been researching all day on how to merge arrays, and make functions with variable parameters. Then it got me thinking, 'can't I combine the two?'. I came up with this function. According to my understanding it should work, but I'm getting errors. Can anyone tell me what I'm doing wrong?
#include <stdio.h>
#include <stdarg.h>
char* merge(int num, ...)
{
va_list list;
char arr[9] = {0};
char *temp;
int i;
int j;
int k=0;
va_start(list,num);
for(i=0;i<num;i++)
{
temp = va_arg(list,char[]);
j = 0;
while(temp[j] != 0x00)
{
arr[k] = temp[j];
j++;
}
k++;
}
va_end(list);
return arr;
}
int main()
{
char data_1[] = "my";
char merged_array[9] = "legs";
int n=0;
//merged_array = merge(1, data_1);
while(merged_array == 0x00)
{
printf("%s\n",merged_array[n]);
n++;
}
}
Perhaps this will help get you started:
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
char* merge(char *arr, int num, ...)
{
va_list list;
int i;
va_start(list,num);
for(i=0;i<num;i++)
strcat(arr, va_arg(list,char *));
va_end(list);
return arr;
}
int main()
{
char data_1[] = "my";
char merged_array[9] = "legs";
merge(merged_array, 1, data_1);
printf("%s\n", merged_array);
return(0);
}

C: Finding duplicate string values in a file

So I have a file containing lets say:
cat
dog
cat
I am trying to go through the file, have it recognize there are two cat elements and one dog element, and then have in the same file edited as:
cat - 2
dog - 1
I already have all the words saved in an array of strings, char **wordList, and I am trying to sort them with qsort and then put it in the format as described above. My qsort functions are:
stringcmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}
void wordSort(char **wordlist)
{
size_t strings_len = numwords - 1;
qsort(wordlist, strings_len, sizeof(char*), stringcmp);
wordFile(wordlist);
}
void wordFile(char **wordlist)
{
if((outFilePtr2 = fopen(outWords, "w")) != NULL)
{
for(x = 1; x < numwords; x++)
{
fputs(wordlist[x], outFilePtr2);
fputs("\n", outFilePtr2);
}
fclose(outFilePtr2);
}
else
{
printf("File\"%s\" could not be opened.\n", outWords);
}
}
It is not sorting anything in order though. How do I fix it?
The following program works with your definition of stringcmp (which seems correct):
int main (int argc, char *argv[]) {
int i;
qsort(argv, argc, sizeof(char *), &stringcmp);
for (i = 0; i != argc; i++) printf("%s\n", argv[i]);
}
Thus I suspect that you have a problem with the definition of char **wordList.
UPDATE
This version slightly modified/completed version of your program works for me:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *outWords = "outWords.txt";
char *wordList[] = { "cat", "dog", "cat" };
#define numwords (sizeof(wordList) / sizeof(wordList[0]))
FILE *outFilePtr2;
int x;
int stringcmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}
void wordSort(char **wordlist)
{
qsort(wordlist, numwords, sizeof(char*), stringcmp);
wordFile(wordlist);
}
void wordFile(char **wordlist)
{
if((outFilePtr2 = fopen(outWords, "w")) != NULL)
{
for(x = 0; x < numwords; x++)
{
fputs(wordlist[x], outFilePtr2);
fputs("\n", outFilePtr2);
}
fclose(outFilePtr2);
}
else
{
printf("File\"%s\" could not be opened.\n", outWords);
}
}
int main() {
wordSort(wordList);
wordFile(wordList);
return 0;
}
I adapted the second argument of qsort (else the last string pointer would not be considered, and left unchanged). I also adapted the initialization x=0 of the for-loop in wordFile for the first string to be printed, too.
You may have defined **wordList in some other way causing a problem, you did not provide the code for it.

Wrong output in my stringreverse program. what is fault in my code?

#include<stdio.h>
#include<conio.h>
#include<string.h>
char* strreverse(char*);
int main()
{
char *rev_string;
char *name="computer";
clrscr();
rev_string=strreverse(name);
printf("%s", rev_string);
getch();
return 0;
}
char* strreverse(char *name)
{
int length=strlen(name);
char *ptr;
char *rstr;
for(ptr=name+(length-1);ptr>=name;ptr--)
{
*rstr=*ptr;
printf("%c",rstr);
rstr++;
}
*(rstr)=NULL;
return rstr;
}
the above is my code. i tried to write a program for string reverse without using arrays. But i am not getting the output retupmoc. what is wrong in my code? how to insert null char in char*?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
char* strreverse(const char*);
int main(){
char *rev_string;
char *name="computer";
clrscr();
rev_string=strreverse(name);
printf("%s\n", rev_string);
free(rev_string);
getch();
return 0;
}
char* strreverse(const char *name){
int length=strlen(name);
const char *ptr;
char *ret, *rstr = malloc(length + 1);
if(ret=rstr){
for(ptr=name+length;ptr != name;){
*rstr++ = *--ptr;
}
*rstr = '\0';
}
return ret;
}
You did not allocate memory to hold your reversed string. Try
char *rstr = calloc(1, length+1);
Also it should be
printf("%c", *rstr); // dereference
*(rstr)= '\0'; // instead of NULL
Here you find sweet and short solution for string reverse:
#include<stdio.h>
#include<string.h>
int strreverse(char* , char*);
int main()
{
char rev_string[10] = {0};
char name[10]="computer";
strreverse(name, rev_string);
printf("%s\n", rev_string);
return 0;
}
int strreverse(char *name, char *rStr)
{
int i = 0;
int length = strlen(name);
while(i < length)
{
rStr[i] = name[length-i-1];
i++;
}
return 0;
}
Try to run and have fun.

Reversing a string in c with recursion

I have written code to reverse a string in c... it works fine but I can't return the reversed string in the main() function.
#include<stdio.h>
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}
it prints the reversed string but I want the reversed string in main(). How can I do this?
Following is one way to reverse string using recursion!
#include <stdio.h>
#include <string.h>
void rev_str_recursive(char arr[], size_t iStart, size_t iLast)
{
if( iStart < iLast )
{
//swap
char temp = arr[iStart];
arr[iStart] = arr[iLast];
arr[iLast] = temp;
rev_str_recursive(arr, ++iStart, --iLast);
}
}
void main()
{
char cArray[] = {"A quick brown fox jumps over a lazy dog"};
rev_str_recursive(cArray, 0, strlen(cArray)-1);
}
You need to modify the string, i.e. the input buffer to reverse(), instead of just printing it.
Doing this recursively seems a bit obnoxious, but should of course be possible.
Basically, I guess the printing becomes an assignment, something like this:
Base: The reversal of an empty string is the empty string.
Step: The reversal of a string begins by swapping the first and last characters, then recursing over the remainder of the string.
Here is another way to reverse a string using recursion:
void reverseString(char* dest, char *src, int len) {
if (src == NULL || len == 0)
return;
reverseString(dest, src + 1, len - 1);
strncat_s(dest, len + 1, src, 1);
}
You can call like that:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STRING "Let's try this one."
#define SIZE 20
void main() {
char* src = (char*)malloc(SIZE);
char* dest = (char*)malloc(SIZE);
strcpy_s(dest, SIZE, "");
strcpy_s(src, SIZE, STRING);
reverseString(dest, src, strlen(src));
/* Do anything with dest. */
// printf("%s\n", dest);
free(src);
free(dest);
}
This code is not executable :(
You define int reverse but reverse function doesnt return any value
instead use this (using void):
#include<stdio.h>
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
void reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}
#include <iostream>
using namespace std;
reverse( char *str)
{
if (*str!='\0')
{
reverse(str+1);
cout<<*str;
}
//cout<<*str when i am just printing here then why this is printing after one space ??
}
int main()
{
string a ;
cin>>a;
reverse(&a[0]);
return 0;
}
a little change in Emre Can Kucukoglu's answer . . .
we can eliminate strncat_s
void revstr_rec(char *sstr, char *dstr, int len)
{
int i = 0;
if((! *sstr) || (! len) )
return;
revstr_rec(sstr + 1, dstr, len - 1);
dstr[len - 1] = *sstr;
return;
}
int main()
{
char *sstr = NULL;
char *dstr = NULL;
sstr = malloc(16);
if(! sstr) {
printf("no memory . . .\n");
return 0;
}
strcpy(sstr, "hello world !");
printf("sstr: %s\n", sstr);
dstr = malloc(16);
if(! dstr) {
printf("no memory . . .\n");
return 0;
}
revstr_rec(sstr, dstr, strlen(sstr));
printf("dstr(recursive): %s\n", dstr);
free(sstr);
free(dstr);
return 0;
}
#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX], *rev;
scanf("%s", str);
rev = reverse(str);
printf("The reversed string is : %s\n", rev);
return 0;
}
char *reverse(char ch[])
{
static char r[MAX];
static int i=0;
if(*ch == '\0') return "";
else
{
reverse(ch+1);
r[i++]=*ch;
}
return r;
}
A simple way with left and right index
void main()
{
char* str = (char*)malloc(strlen("somestring")+1);
strcpy(str, "somestring");
int leftIndex = 0;
int rightIndex = strlen(str) - 1;
printf("%s\n", ReverseString(str, leftIndex, rightIndex));
free(str);
}
char* ReverseString(char* str, int leftIndex, int rightIndex)
{
if (leftIndex == rightIndex || leftIndex == (rightIndex +1)) {
return str;
}
// flip letters
char leftLetter = *(str + leftIndex);
char rightLetter = *(str + rightIndex);
*(str + leftIndex) = rightLetter;
*(str + rightIndex) = leftLetter;
return ReverseString(str, leftIndex+1, rightIndex -1);
}
use sprintf it will print your reversed string into buffer.
#include<stdio.h>
char *b;
main()
{
char a[17]="abcdefg";
char buffer[17];
buffer[0]= '\0';
b = buffer;
reverse(a);
printf("%s\n",buffer);
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
sprintf(b,"%c",*a);
b++;
}
}
void palindromo(char *s)
{
if(s[0] != '\0'){
palindromo(s+1);
printf("%c", s[0]);
}
}
This is a small recursive function who print the string inverted.
#include<stdio.h>
#include<string.h>
void rev(char *);
int main()
{
char s[]="Hello";
printf("\n%s",s);
rev(s);
printf("\n%s",s);
return 0;
}
void rev(char *s)
{
static int i=0;
static int j=0;
if(j==0) //since static variable can be intitialized
{ //only with a constant literal,to store
j=strlen(s)-1; //length-1 in 1st function call, we can use
} //this trick.(condition satisfied only in 1st
//function call)
if(i<j)
{
char temp;
temp=s[i];
s[i]=s[j]; //Analogous to for(i=0,j=l-1;i<j;i++,j--)
s[j]=temp; // { //swap code }
i++;
j--;
rev(s);
}
}
#include<stdio.h>
void reverse(char *a);
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
void reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}

Resources