c语言实现判断字符串最后一个字符
时间: 2023-11-21 18:06:02 浏览: 160
要判断字符串中的最后一个字符,你可以使用C语言中的数组和字符串操作函数。以下是一种实现方法:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[20];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
if (len > 0) {
char lastChar = str[len - 1];
printf("字符串的最后一个字符是:%c\n", lastChar);
} else {
printf("字符串为空。\n");
}
return 0;
}
```
这段代码首先声明了一个长度为20的字符数组 `str`,用于存储输入的字符串。然后使用 `scanf` 函数接收用户输入的字符串。接下来,使用 `strlen` 函数获取字符串的长度,存储在变量 `len` 中。
如果字符串长度大于0,则说明字符串非空。我们可以通过 `str[len - 1]` 来获取最后一个字符,并将其存储在变量 `lastChar` 中。最后,使用 `printf` 函数打印出最后一个字符。
请注意,这段代码假设输入的字符串不超过20个字符,如果超过了该限制,可能会导致数组越界。在实际应用中,需要根据实际需求对代码进行适当的修改和错误处理。
相关问题
c语言实现回文字符串判断
以下是一个C语言实现回文字符串判断的例子:
```c
#include <stdio.h>
#include <string.h>
int isPalindrome(char *str) {
int i, j;
int len = strlen(str);
for (i = 0, j = len - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
return 0;
}
}
return 1;
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
if (isPalindrome(str)) {
printf("是回文字符串\n");
} else {
printf("不是回文字符串\n");
}
return 0;
}
```
C语言判断一个字符串是不是回文字符串
以下是两种C语言判断一个字符串是否为回文字符串的方法:
方法一:
```c
#include <stdio.h>
#include <string.h>
int judge();
int main() {
int i;
i = judge();
if (i == 1) {
printf("该字符串是回文。\n");
} else if (i == 0) {
printf("该字符串不是回文。\n");
}
}
int judge() {
char a[50];
int length;
int i;
gets_s(a);
length = strlen(a);
for (i = 0; i < length/2; i++) {
if (a[i] != a[length - i - 1]) {
return 0;
} else {
return 1;
}
}
}
```
方法二:
```c
#include <stdio.h>
#include <string.h>
#define N 100
int main() {
char s[N];
int i=0,j;
printf("Input a String: \n");
//输入一个字符串赋值给s
gets(s);
//j的初始值为s字符串最后一个位置
j=strlen(s)-1;
//进行while判断i、j的位置和i、j位置的值的关系
while(i<=j&&s[i]==s[j]){
//每比较一次就i右移、j左移一位
i++;
j--;
}
//判断最终i和j的的位置
//根据i、j的位置最终是会互相超越的,所以如果i<=j说明存在对应位置不等的情况就是不是回文串
if (i<=j) {
printf("不是回文字符串\n");
} else{
printf("是回文字符串\n");
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)