Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I slice a string in c#? [closed]

Tags:

string

c#

slice

string word = "hello";

So what I want to do is slice the string so that I can print, for example, elloh to the console window. In python it's so simple but I'm not sure if there's a specific method for slicing in c#.

like image 436
Ali Appleby Avatar asked Jan 05 '14 00:01

Ali Appleby


People also ask

Can we slice Strings in C?

lets we take input from user and if string length is greater than 10 we slice first 5 string and print out next 5 string to the console. We will need to function that we custom create without string functions that available in c library. One is string length checker and 2nd is to slice string.

How do you slice a string?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.

Can we slice strings?

Slicing StringsYou can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.

Does C have slicing?

Yes, it is possible using the function memcpy .


2 Answers

A string can be indexed to get characters:

string word = "hello";
char h = word[0];

or strings have methods for "slicing":

int start = 0;
int length = 1;
string h = word.Substring(start, length);

Why not read the docs and find out for yourself?

like image 181
spender Avatar answered Oct 09 '22 04:10

spender


There's no exact translation from the concept of a slicing, but a Substring is generally what you want.

It is unclear to me what your exact criteria is to slice it up, but this would do what you want:

void Main()
{
    var input = "hello";
    var output = input.Substring(1, input.Length - 1) + input.Substring(0, 1);

    Console.WriteLine (output);
}
like image 20
Jeroen Vannevel Avatar answered Oct 09 '22 03:10

Jeroen Vannevel