在C#中拼接字符串

时间:2018-10-21 19:20:29

标签: c# python-2.7

如何在C#中拼接字符串?我如何将以下python代码转换为C#?

string = "this is a string"

string[-1]          ## last letter
string[:2]           ## first 2 letters
string[2:]           ## letters after 2nd letter
string[-2]            ## last 2 letters

words = string.split()    ## list of words 
## ["this","is","a","string"]
string_again = " ".join(words)  ## list of words back to 
## string

2 个答案:

答案 0 :(得分:3)

我很感谢跨语言的介绍,因为有些事情对于Google来说并不容易。尝试寻找“ Python到C#速查表”

//py
string = "this is a string"
//c#
string myStringName = "this is a string";
var myStringName = "this is a string";
String myStringName = "this is a string"

//py
string[-1]          ## last letter
//c#
char c = myStringName[myStringName.Length-1];

//py
string[:2]           ## first 2 letters
//c#
string firstTwo = myStringName.Remove(2);

//py
string[2:]           ## letters after 2nd letter
//c#
string remainder = myStringName.Substring(2);

//py
string[-2]            ## last 2 letters
//c#
string lastTwo = myStringName.Substring(mystringName.Length - 2);

//py
words = string.split()    ## list of words 
//c#
myStringName = "this,is,a,string";
string[] strArray = myStringName.Split(',');

//py
string_again = "".join(words)  ## list of words back to 
//c#
string stringWithCommasAgain = string.Join(",", strArray);

答案 1 :(得分:0)

C#8现在为https://dzone.com/articles/how-to-optimize-mysql-queries-for-speed-and-perfor提供了与Python的切片符号一样简洁的语法。

string myString = "this is a string";

myString[^1]         // last letter
myString[..2]        // first 2 letters
myString[2..]        // letters after 2nd letter
myString[^2]         // second to last letter 
myString[^2..]       // last 2 letters

var words = myString.Split();                // list of words 
var string_again = string.Join(" ", words);  // list of words back to string