switch case 输出字符串
时间: 2023-11-21 12:53:16 浏览: 33
可以使用switch case语句输出字符串的ASCII码。具体实现方法如下:
1.将字符串转换为字符数组。
2.遍历字符数组,将每个字符转换为对应的ASCII码。
3.使用switch case语句根据ASCII码输出对应的字符。
以下是示例代码:
```
String str = "Hello World";
char[] chars = str.toCharArray();
for(char c : chars){
int ascii = (int)c;
switch(ascii){
case 65:
System.out.print("A");
break;
case 66:
System.out.print("B");
break;
//其他字母的ASCII码省略
default:
System.out.print(" ");
break;
}
}
```
输出结果为:HELLO WORLD
相关问题
switch case判断字符串java
可以使用switch case来判断字符串,但是这个功能只适用于Java SE 7及以上版本。在之前的版本中,只能使用if-else语句。
以下是一个使用switch case判断字符串的示例代码:
```
String str = "hello";
switch(str) {
case "hello":
System.out.println("你好!");
break;
case "world":
System.out.println("世界!");
break;
default:
System.out.println("未知的字符串!");
}
```
根据字符串的值,程序将会输出相应的结果。在示例代码中,如果变量str的值是"hello",那么程序将会输出"你好!"。如果变量str的值是"world",那么程序将会输出"世界!"。如果变量str的值既不是"hello"也不是"world",那么程序将会输出"未知的字符串!"。
switch case 字符串
在 C++ 11 之后,支持使用字符串作为 switch case 条件。具体实现方式可以使用 std::string 或者 char[] 类型来表示字符串,然后使用常量表达式来作为 case 条件。下面是一个示例代码:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello";
switch (str[0]) {
case 'h':
cout << "The first letter is h" << endl;
break;
case 'w':
cout << "The first letter is w" << endl;
break;
default:
cout << "The first letter is neither h nor w" << endl;
}
return 0;
}
```
在上面的代码中,我们使用 std::string 类型表示字符串,并且使用 str[0] 来获取字符串的第一个字符。然后我们使用 switch case 来判断第一个字符是不是 'h' 或者 'w'。如果是,就输出对应的信息,否则输出默认信息。