编写程序,提示用户输入一个字符串,显示他的长度,第一个字符和最后一个字符符
时间: 2024-03-27 18:38:26 浏览: 29
好的,以下是 Java 编写的程序,用于提示用户输入一个字符串,显示其长度、第一个字符和最后一个字符:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String inputString = scanner.nextLine();
int length = inputString.length();
char firstChar = inputString.charAt(0);
char lastChar = inputString.charAt(length - 1);
System.out.println("您输入的字符串长度为:" + length);
System.out.println("您输入的字符串第一个字符为:" + firstChar);
System.out.println("您输入的字符串最后一个字符为:" + lastChar);
}
}
```
这个程序会打印出提示信息,让用户输入一个字符串,然后计算字符串的长度,并获取第一个字符和最后一个字符,最终将这些信息打印出来。
相关问题
用JAVA编写一个程序,提示用户输入一个字符串,显示它的长度和第一个字符
的ASCII码值。
代码如下:
```java
import java.util.Scanner;
public class StringLengthAndASCIICode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个字符串:");
String str = scanner.nextLine();
int length = str.length();
char firstChar = str.charAt(0);
int asciiCode = (int) firstChar;
System.out.println("该字符串的长度为:" + length);
System.out.println("该字符串的第一个字符为:" + firstChar);
System.out.println("该字符串的第一个字符的ASCII码值为:" + asciiCode);
}
}
```
运行结果如下:
```
请输入一个字符串:hello world
该字符串的长度为:11
该字符串的第一个字符为:h
该字符串的第一个字符的ASCII码值为:104
```
c语言编写一个程序,用户输入任意一个字符串,显示它的长度和第一个字符
您好,感谢您的问题!这是一道经典的字符串处理问题,我可以为您提供以下 C 代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
printf("输入的字符串长度为:%lu\n", strlen(str));
printf("输入的字符串第一个字符为:%c\n", str[0]);
return 0;
}
```
在这个程序中,我们首先定义了一个字符数组 `str`,并使用 `scanf` 函数从键盘输入一个字符串。接下来,使用 `strlen` 函数计算字符串长度,并使用数组下标 `[]` 获取第一个字符并输出即可。
需要注意的是,由于我们没有对用户输入字符串的长度做出任何限制,因此需要事先定义足够大的数组来存放输入的字符串,这里我们定义了大小为 100 的字符数组。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![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)