前言
本文將演示如何將字符串的單詞倒序輸出。注意:在這里我不是要將“john” 這樣的字符串倒序為成“nhoj”。這是不一樣的,因為它完全倒序了整個字符串。而以下代碼將教你如何將“你 好 我是 緹娜”倒序輸出為“緹娜 是 我 好 你”。所以,字符串的最后一個詞成了第一個詞,而第一個詞成了最后一個詞。當然你也可以說,以下代碼是從最后一個到第一個段落字符串的讀取。
對此我使用了兩種方法。
第一種方法僅僅采用拆分功能。
根據空格拆分字符串,然后將拆分結果存放在一個string類型的數組里面,將數組倒序后再根據索引打印該數組。
代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
using system; using system.collections.generic; using system.linq; using system.text; namespace 將字符串的單詞倒序輸出 { class program { static void main( string [] args) { console.foregroundcolor = consolecolor.white; console.writeline( "請輸入字符串:" ); console.foregroundcolor = consolecolor.yellow; string s = console.readline(); string [] a = s.split( ' ' ); array.reverse(a); console.foregroundcolor = consolecolor.red; console.writeline( "倒序輸出結果為:" ); for ( int i = 0; i <= a.length - 1; i++) { console.foregroundcolor = consolecolor.white; console.write(a[i] + "" + ' ' ); } console.readkey(); } } } |
輸出結果
第二種方法
我不再使用數組的倒序功能。我只根據空格拆分字符串后存放到一個數組中,然后從最后一個索引到初始索引打印該數組。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
using system; using system.collections.generic; using system.linq; using system.text; namespace 將字符串的單詞倒序輸出 { class program { static void main( string [] args) { console.foregroundcolor = consolecolor.white; console.writeline( "請輸入字符串:" ); console.foregroundcolor = consolecolor.yellow; int temp; string s = console.readline(); string [] a = s.split( ' ' ); int k = a.length - 1; temp = k; for ( int i = k; temp >= 0; k--) { console.write(a[temp] + "" + ' ' ); --temp; } console.readkey(); } } } |
輸出結果
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家學習或者使用c#能帶來一定的幫助,如果有疑問大家可以留言交流。
原文鏈接:http://www.cnblogs.com/Yesi/p/5875031.html