2013-09-11 123 views
1

我檢查了大多數問題可能包含我的解決方案,但我找不到任何問題。或者,也許我不明白。所以,這是我的問題:如何在一個字符串中組合兩個不同的字符串?

我想將兩個字符串結合在一起並單獨使用它。

我的字符串:

static string name = ""; (for example: John or Jane) 
    static string gender = ""; (for example: Mr. or Mrs.) 

,我想這兩個在一個像這樣的組合:

static string player = gender+name; 

    Console.writeline("Hello "+player); 

,我想看到它在我的控制檯是這樣的:

Hello Mr.John or Hello Mrs.Jane 

我不想提及console.readline部分。將會有我將輸入姓名和性別的條目。 感謝

編輯:

這是我做的(對不起,這要花很長時間):

static string name = ""; 
    static string gender = ""; 
    static string player = name + gender; 
    static void Main(string[] args) 
    { 

     Console.WriteLine("Welcome. What is your name?"); 
     name = Console.ReadLine(); 
     Console.WriteLine("Sex?\n-Male\n-Female"); 
     gender = Console.ReadLine(); 
     Console.WriteLine("Press Enter to continue"); 
     Console.ReadLine(); 
     Console.WriteLine("Welcome"+player); 

     Console.ReadLine(); 
    } 

這些結果,如 「歡迎__

+4

我沒有看到問題... – UIlrvnd

+0

你有沒有試過這個? –

+0

你已經做到了 - static string player = gender + name; – Lev

回答

0

問題是玩家應該是一個函數,而不是一個字符串。

String Player() 
{ 
    return gender + name; 
} 

這必須在您的主要功能之外。

0

你讀namegender但您從未將它們組合到一起,因此player仍爲空字符串。

做到這一點,而不是:

player = gender + name; 
Console.WriteLine("Welcome "+player); 
1

的這裏的問題是,player是在類的初始化計算。所以基本上你要結合string.Emptystring.Empty。每次使用前不計算Player

因此,在使用它之前,您可以只使用player = name + gender;,但一個好的做法是使用限制變量的變量。由於您在Main中使用了名稱和性別,因此請使用局部變量。

static void Main(string[] args) 
{ 
    string name; 
    string gender; 

    Console.WriteLine("Welcome. What is your name?"); 
    name = Console.ReadLine(); 

    Console.WriteLine("Sex?\n-Male\n-Female"); 
    gender = Console.ReadLine(); 

    Console.WriteLine("Press Enter to continue"); 
    Console.ReadLine(); 

    Console.WriteLine("Welcome " + gender + name); 

    Console.ReadLine(); 
} 

如果你願意,你也可以做

string player = gender + name; 
Console.WriteLine("Welcome " + player); 

,但我認爲意圖是沒有臨時變量不夠清晰。如果你需要更復雜的格式,你也可以string.Format,它比一堆+運營商更乾淨。

Console.WriteLine(string.Format("Welcome, {0} {1}!", gender, name)); 
0
Console.ReadLine(); 
player = gender+name; 
Console.WriteLine("Welcome"+player); 

這將設置字符串來他們一直在讀什麼作爲。 您還需要一個if語句將fe/male更改爲mr/s。

0

如果你想合併沒有分隔符的字符串,你可以使用String.Concat(string firstString,string secondString)。你可以使用String.Join(string separator, string[] stringsToBeJoined)。第一個參數是合併單個字符串中字符串之間的分隔符,第二個參數是將要合併的字符串數組。

相關問題