Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.substring vs string.take

Tags:

If you want to only take a part of a string, the substring method is mostly used. This has a drawback that you must first test on the length of the string to avoid errors. For example you want to save data into a database, and want to cut off a value to the first 20 characters.

If you do temp.substring(0,20) but temp only holds 10 chars, an exception is thrown.

There are 2 solutions that I see :

  1. test on the length, and do the substring if needed
  2. use the extension method Take

        string temp = "1234567890";     var data= new string( temp.Take(20).ToArray());     --> data now holds "1234657890" 

Is there any disadvantage in terms of speed or memory use , when one uses the Take method. The benefit is that you do not have to write all those if statements.

like image 607
Williams Avatar asked Mar 14 '13 09:03

Williams


People also ask

What is the difference between a string and a substring?

a substring is a subsequence of a string in which the characters must be drawn from contiguous positions in the string. For example the string CATCGA, the subsequence ATCG is a substring but the subsequence CTCA is not.

Is substr () and substring () are same?

The difference between substring() and substr() The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .

Which is faster split or substring?

When you run this multiple times, the substring wins on time hands down: 1,000,000 iterations of split take 3.36s, while 1,000,000 iterations of substring take only 0.05s.

Should I use substring or slice?

We recommend using slice() over substring() unless you need the argument swapping feature. The negative numbers feature is extremely useful, and it is easier to remember than the difference between substring() and substr() .


1 Answers

If you find yourself doing this a lot, why not write an extension method?

For example:

using System;  namespace Demo {     public static class Program     {         public static void Main(string[] args)         {             Console.WriteLine("123456789".Left(5));             Console.WriteLine("123456789".Left(15));         }     }      public static class StringExt     {         public static string Left(this string @this, int count)         {             if (@this.Length <= count)             {                 return @this;             }             else             {                 return @this.Substring(0, count);             }         }     } } 
like image 120
Matthew Watson Avatar answered Mar 17 '23 07:03

Matthew Watson