Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splicing strings in C#

Tags:

python

c#

How do you splice strings in C#? how would i translate the following python code into 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
like image 456
Noah Jones Avatar asked Jan 27 '23 06:01

Noah Jones


1 Answers

I appreciate that cross-langing is hard because some things just aren't easy to google for. Try looking for a "Python to C# cheatsheet"

//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);
like image 86
Caius Jard Avatar answered Feb 08 '23 04:02

Caius Jard