Finding last character - c

I'm new to C and trying to create a function that check a string and returns the last character.
I get the function to print the correct letter, but I cant figure out how to return it :/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char last_chr(char *c);
int main (int argc, const char * argv[]) {
char *text[15];
strcpy(text, "*find:last;char#");
last_chr(text); //debugging
//printf("last char: %c", last_chr(text)); //not working
return 0;
}
char last_chr(char *c) {
char *endchr;
char result;
int pos = strlen(c)-1;
endchr = c[pos];
//sprintf(result,"%s",endchr); //"EXEC_BAD_ACCESS"
putchar(endchr); //prints #
//putc(endchr, result); //"EXEC_BAD_ACCESS"
//printf(endchr); //"EXEC_BAD_ACCESS"
return result;
}

You don't assign result. You probably mean
result = c[pos];
instead of endchr = c[pos];
endchr is a character-pointer instead of a character.

#include <stdio.h>
#include <string.h>
char last_chr(char *c);
int main (int argc, const char * argv[]) {
char text[32];//char *text[15]
strcpy(text, "*find:last;char#");//length is 17
printf("last char: %c", last_chr(text));//#
return 0;
}
char last_chr(char *c) {
if(c == NULL || *c == '\0') return 0;
return c[strlen(c)-1];
}

Related

Remove multiple characters from string

I'm trying to creat a program that removes all occurences from a character that I choose from a certain string and also returs the number of characters that were removed.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIMV 10
int eliminar(char texto[], char ch, char novoTexto[]){
int a=0,i;
for(i=0; texto[i] != '\0';i++){
texto[i] = texto[i+a];
novoTexto[i]=texto[i];
if(novoTexto[i]==ch){
novoTexto[i] = '\0';
a++;
}
}
return a;
}
int main()
{
char frase[]="Uma arara torta!";
char res[50];
printf("%s\n",frase);
printf("%d\n",eliminar(frase,'r',res));
printf("%s\n",res);
return 0;
}
When I run the program, it returns:
Uma arara torta!
3
Uma a
What I wanted to return is:
Uma arara torta!
3
Uma aaa tota!
It's a silly question but I can't find the mistake that I made. Thank you!
Putting '\0' means to terminate the string there.
You have to skip adding characters to eliminate.
Try this:
int eliminar(char texto[], char ch, char novoTexto[]){
int a=0,i,j=0;
for(i=0; texto[i] != '\0';i++){
if(texto[i]==ch){
a++;
}else{
novoTexto[j]=texto[i];
j++;
}
}
novoTexto[j]='\0';
return a;
}
Putting '\0' means to terminate the string there.
check this:
int eliminator(char * texto, char ch, char * novoTexto) {
int i=0;
while(*texto != '\0') {
if (*texto == ch) {
texto++;
++i;
} else {
*novoTexto++ = *texto++;
}
}
*novoTexto = '\0';
return i;
}
int main(int arg, char **argv) {
char frase[] = "Uma arara torta!";
char res[50];
printf("%s\n",frase);
printf("%d\n",eliminator(frase, 'r', res));
printf("%s\n",res);
}

Read String Length in C - Cannot use <string.h>

How can I determine how many characters are in a string?
The problem I face is the stipulation that I cannot use the <string.h> library.
Here is what I'm trying to solve:
#include <assert.h>
#include <stdio.h>
#define MAX_LENGTH 1024
int string_length(char *string);
int main(int argc, char *argv[]) {
assert(string_length("") == 0);
assert(string_length("!") == 1);
assert(string_length("Hello, world!") == 13);
assert(string_length("17... seventeen.\n") == 17);
printf("All tests passed. You are awesome!\n");
return 0;
}
int string_length(char *string) {
// Add code here
return 0;
}
All the strings in C end with a special char \0 so you just need to check how many chars there are before that char.
int string_length(char *string) {
int chars = 0;
while(*string != '\0'){
chars++;
string++;
}
return chars;
}

Convert string to integer recursive - c programming

I'm trying to convert a string containing a number. The number is thousand separated with a dot. I've made a simple solution with sscanf(input, "%i.%i", &first, %second); return first * 1000 + second;
This works alright, but it has its limitations as it only works for numbers below 1.000.000. I've tried making this recursive, but my program wont compile. Maybe one of you guys, can see whats wrong.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* concat(const char *s1, const char *s2) {
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
strcpy(result, s1);
strcat(result, s2);
return result;
}
char *convert_spectators( char *input) //
{
char fir[3], sec[100];
int scan_res = sscanf(input, "%3[0123456789]%*[^0123456789]%s", fir, sec);
if (scan_res == 2) {
return concat(fir, convert_spectators(sec));
} else if (scan_res == 1) {
return fir;
}
}
int main() {
printf("Result: %i\n", atoi(convert_spectators("123.456.789")));
return 1;
}
from convert_spectators() you are returning "fir", which is a local array. It is wrong. I modified your code and passing fir and sec from calling function.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* concat(const char *s1, const char *s2) {
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
strcpy(result, s1);
strcat(result, s2);
return result;
}
char *convert_spectators( char *input, char *fir, char *sec) //
{
int scan_res = sscanf(input, "%3[0123456789]%*[^0123456789]%s", fir, sec);
if (scan_res == 2) {
char firTemp[4] = "";
char secTemp[100] = "";
return concat(fir, convert_spectators(sec, firTemp, secTemp));
} else if (scan_res == 1) {
return fir;
} else {
printf("Something wrong, scan_res[%d]\n", scan_res);
return NULL;
}
}
int main() {
char fir[4] = "";
char sec[100] = "";
printf("Result: %i\n", atoi(convert_spectators("123.456.789", fir, sec)));
return 1;
}
This can be accomplished without scanf
int convert(char *s, int n) {
if (!*s || n >= 1000000000)
return n;
if (*s >= '0' && *s <= '9')
n = n * 10 + *s - 48;
return convert(s+1, n);
}
int main() {
char *str = "123.456.789";
printf("%d\n", convert(str, 0));
}
This will just parse through the string, and skip any characters that aren't digits. And stop at the end of the string or when result overflows 32 bits.
As mentioned, your way of concatenating each substring and converting to an integer is fine, but you are returning a local array in your function convert_spectators(). You need to declare that array locally before you call the function, or make it global.

conflicting types for function returning a char array

Here's my code:
#include <stdio.h>
#include <string.h>
char input_buffer[1000];
void get_substring(){
int i;
int length;
printf("Please enter a string:\n");
scanf("%[^\n]s", input_buffer);
printf("Index of first character of substring:\n");
scanf("%d", &i);
printf("Length of substring:\n");
scanf("%d", &length);
printf("Substring is %.*s ", length, input_buffer + i);
}
int main(void) {
// your code goes here
//get_substring(0,4);
get_substring();
return 0;
}
That's my current code, I want to return a pointer of the input, instead of just displaying the substring. Sorry for the confusion everyone.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getSubstring(char* str,size_t start, size_t length)
{
// determine that we are not out of bounds
if(start + length > strlen(str))
return NULL;
// reserve enough space for the substring
char *subString = malloc(sizeof(char) * length);
// copy data from source string to the destination by incremting the
// position as much as start is giving us
strncpy(subString, str + start, length);
// return the string
return subString;
}
int main(int argc, char* argv[])
{
char *str = "Hallo Welt!";
char *subStr = getSubstring(str,0,20);
if(subStr != NULL)
{
printf("%s\n",subStr);
free(subStr);
}
}
This solution should give you a hint how you would start with such a problem.

I need to know how many times a string appears within another one! Using C

Well, the title already says what I need. I tried to use a loop but it didn't go well, so, I came for your help guys!
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char word[31], word2[31];
int size1, size2;
int i, j, k; // control
int count = 0;
printf ("\nInput the first word");
scanf ("%s", word);
printf ("\nInput the second word: ");
scanf (" %s", word2);
// I tried to make a loop through the first string and if it matches a letter, it would loop through the others (if they are equal, we have a substring), but failed to put it on the `for` loop
printf ("'%s' appears %d times within '%s'", word2, count, word);
return 0;
}
strstr is a useful function, it shortens your code considerably; when you find a match, just try again with the rest of the string;
#include <string.h>
#include <stdio.h>
int main()
{
const char* source = "aabaa";
const char* string2find = "aa";
int occurrences;
const char *ptr, *lastfind = NULL;
for(ptr=source; (lastfind=strstr(ptr, string2find)); ptr=lastfind+1)
occurrences++;
printf("%d\n", occurrences);
return 0;
}
...or if you're really set on doing it without string.h functions, the code gets a bit more verbose;
#include <string.h>
#include <stdio.h>
int main()
{
const char* source = "aaabaa";
const char* string2find = "aa";
int count=0;
const char *position;
for(position=source; *position; position++) {
int comparepos, equal=1;
for(comparepos=0; string2find[comparepos]; comparepos++) {
if(position[comparepos] != string2find[comparepos]) {
equal = 0;
break;
}
}
count+=equal;
}
printf("%d\n", count);
return 0;
}
Use strstr to find occurence of string in other string:
#include <stdio.h>
#include <string.h>
int main () {
char* a = "aaaa";
char* b = "aa";
char* c;
int count = 0;
for(c = a; *c; c++){
if(strstr(c, b)){
count++;
}
}
printf("count %d\n", count);
}
Also, use strlen to find length of a string..

Resources