Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking last char of string in c

Tags:

c

string

If I have two types of strings as:

const char *str1 = "This is a string with \"quotes escaped at the end\""; 
const char *str2 = "This is a \"string\" without quotes at the end"; 

testFn(str1);
testFn(str2);

int testFn(const char *str)
{
  // test & return 1 if ends on no quote
  // test & return 0 if ends on quote
  return;
}

I would like to test if the string ends with a quote " or not

What would be a good way of testing this? Thanks

like image 957
radar75 Avatar asked Apr 07 '10 21:04

radar75


People also ask

How do you find the last position of a character in a string in C?

strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .

What is the last character of a string in C?

Strings are actually one-dimensional array of characters terminated by a null character '\0'.

How do you read the last character of a string?

Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.

What is last character of string?

The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .


2 Answers

Don't forget to make sure your string has at least 1 character:

int testFn(const char *str)
{
    return (str && *str && str[strlen(str) - 1] == '"') ? 0 : 1;
}
like image 50
R Samuel Klatchko Avatar answered Oct 21 '22 05:10

R Samuel Klatchko


int testFn(const char *str)
{
  return !str || !*str || str[strlen(str) - 1] != '\"';
}
like image 26
Péter Török Avatar answered Oct 21 '22 04:10

Péter Török