Click here to Skip to main content
15,886,046 members
Everything / General Programming / String

String

string

Great Reads

by Michael Sydney Balloni
Different languages and approaches are evaluated for a file and string processing benchmark
by fabio bussu
MatchKit is a .NET Library that provides a set of classes to build patterns to match simple and complex strings
by honey the codewitch
How to provide custom formatters for string.Format() in C#
by honey the codewitch
BinaryReader needs a better way to read strings and types. Here's a quick and dirty fix

Latest Articles

by Xavier Junqué i de Fortuny
Converts MathML coded string to/from plain text string
by Jovibor
String to number conversion library, for char and wchar_t strings
by Michael Sydney Balloni
Different languages and approaches are evaluated for a file and string processing benchmark
by Brian C Hart
Example of how to use the caret (^) in Regexes that have specific matching requirements

All Articles

Sort by Score

String 

27 Sep 2022 by Michael Sydney Balloni
Different languages and approaches are evaluated for a file and string processing benchmark
21 Apr 2014 by fabio bussu
MatchKit is a .NET Library that provides a set of classes to build patterns to match simple and complex strings
13 Mar 2020 by honey the codewitch
How to provide custom formatters for string.Format() in C#
23 Apr 2021 by honey the codewitch
BinaryReader needs a better way to read strings and types. Here's a quick and dirty fix
12 Apr 2015 by Jeffijoe
Writing properly formatted, grammatically correct, translatable UI messages
21 Aug 2016 by OriginalGriff
Because the width of a string is not the sum of the widths of all teh characters, except in non-proportional (or fixed width) fonts.In a fixed width font all characters are the same width, so the string is the width of a character times the number of characters:WIIIIILL12222234But in a...
20 Jan 2011 by dasblinkenlight
If you have not studied dictionaries yet, recall that char values can be used as an array index (it's simply a number between 0 and char.MaxValue). If you create an array of counters, you'd be able to run through the characters in your string with a foreach loop, incrementing your counters along...
13 Jun 2012 by Manfred Rudolf Bihy
It will work if you insert the periods quoted:string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:0'.'0'.'000}",10024);The output string will be: "1.0.024"Regards,Manfred
18 May 2010 by xprog
Algorithm to convert Arabic Numbers to Arabic Text using C#
21 Jan 2011 by Yusuf
Hello Rupa, Your professor here. I gave the assignment to do it yourself, not to re-assign it to others. I need to see you in the classroom.
25 May 2011 by Nithin Sundar
I had the same problem. You can do something like this.This is for MFC.CString sAttributes; //Form the attributes stringsAttributes += "DSN=";sAttributes += YOUR DSN NAME;sAttributes += '\0';sAttributes += "Server=";sAttributes += SERVER NAME;sAttributes += '\0';You...
28 Dec 2011 by Abhinav S
TryHow to export to Excel from vb.net code. [^]Export to Excel using VB.Net[^]
14 Apr 2012 by VJ Reddy
One option is to split the original string at the location of ? and reconstruct using @param as shown belowSub Main Dim statement As String = "INSERT INTO X (a,b,c) values (?,?,?)" Dim statements As String() = statement.Split("?"C) 'Construct a stringbuilder Dim sb As New...
7 Jun 2012 by VJ Reddy
If your purpose is to find the Cell in the DataGridView containing a given Text, then I think it is better to use the Rows and Cells collection of DataGridView to generate a List of DataGridViewCell which contain the given text. Then on a button click set the CurrentCell of DataGridView to the...
9 Oct 2012 by Sergey Alexandrovich Kryukov
This not "convert" (this word is a real curse of CodeProject inquirers, I don't know why), this is...
19 Nov 2012 by Jim Meadors
String manipulation of XML files
24 Jan 2014 by OriginalGriff
Try:string myString = "('" + string.Join("', '", permissionsRequired) + "')";(You don't need the ToArray - String.Join has an IEnumerable override: http://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx[^])
15 Feb 2014 by OriginalGriff
No - you can't do that, because strings are immutable, which measn that once a string has been created, you cannot change it in any way. If you want to extract part of a string, then you need to create a new string from the existing one: string DOB = "10/10/1992"; ...
16 Sep 2014 by BillWoodruff
There are legal (liability), as well as scientific, reasons one should not attempt to automate extracting summary data from clinical reports like this one. Such automated extracted data used by medical staff without the training to appreciate the subtleties involved could lead to negligent, or...
23 Sep 2014 by Sergey Alexandrovich Kryukov
There is no such thing as "UTF string" per se. String in .NET is always a Unicode string, never anything else.If you have a string and encode it as UTF (any UTF), it's the array of bytes. Different encodings can give you different bytes from the same string. Unicode defines one-to-one...
12 Oct 2014 by Fredrik Bornander
How crazy do you want to go?If you're up for some un-safe code you can go ~70% faster by using pointers;public unsafe static bool IsStringMadeOf3(this string str, string from) { char[] copy = new char[from.Length]; from.CopyTo(0, copy, 0, copy.Length); fixed (char* s = str)...
28 Oct 2014 by PIEBALDconsult
Perform the replacements in reverse order. And you may want to use intermediate values.And do you really need to check to see whether or not the string contains the value first?I recommend performing the setText only at the end.As you have it, you'll be scanning the string a great...
27 Jan 2015 by HiDensity
Class providing methods to count up a string using a definable character set.
20 Aug 2015 by Sergey Alexandrovich Kryukov
By default, C string is marshaled as .NET string in P/Invoke. To be certain, you can use the attribute System.Runtime.InteropServices.MarshalAsAttribute:https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute%28v=vs.110%29.aspx[^].The attribute should be...
15 Mar 2016 by Jochen Arndt
It is returning a length of 350 because the string contains 350 characters.To verify this, select the text and paste it into an Unicode editor (e.g. with Notepad++ choose File - New, Encoding - UCS-2 Little Endian, and paste the text). Within Notepad++, it will look like (shortened, there...
17 Jan 2017 by OriginalGriff
You would have to say:if (dog != "cat" && dog != "cow")Orif (!(dog == "cat" || dog == "cow"))
7 Oct 2019 by phil.o
string substr (size_t pos = 0, size_t len = npos) const; The second parameter holds for the length of the substring, not for the index of the end of the capture. std::string::substr[^] So, yes, the function is working properly; you just misused its parameters :)
2 Aug 2023 by OriginalGriff
No, because String s1 = "mynameisbond"; uses a single string literal and String s2 = "myname" + "isbond"; uses two that can be combined at compile time into a single literal. But s5, s6, and s7 all get assigned at run time, not compile - so...
11 Jan 2011 by #realJSOP
It's certainly the fastest way to type it.If you want to try to find faster ways, be a programmer and try different ways to approach the problem.Performance for such a task would greatly depend on the length of the string involved.
12 Jan 2011 by Not Active
I don't understand where the writing to com port comes in or why you are using Thread.Sleep()?StringBuilder sb = new StringBuilder();foreach(Char c in textBox1.Text){ sb.Append(c); if(!Char.IsWhiteSpace(c)) { sb.Append("x"); }}textBox2.Text =...
25 May 2011 by dhpatil861984
struct testfunctor{void operator()(char& c) { if(c == '|') c = '\0'; }};std::for_each( str.begin(), str.end(), testfunctor() );This should work..
1 Feb 2012 by Sergey Alexandrovich Kryukov
Well, it means the string cannot be parsed as System.DateTime. You need to specify expected format. The right approach is...
11 Apr 2012 by Mehdi Gholam
Use :(?\(\s*\?.*)+Which will give you the (...) portion and then just count the number of ? chars and replace with @paramN where N is an iterator.
25 Apr 2012 by Mario Majčica
Does this help?using System;using System.Text.RegularExpressions;class Program{ static void Main() { string value = "cat\r\ndog\r\nanimal\r\nperson"; // // Split the string on line breaks. // ... The return value from Split is a string[] array. //...
21 Jun 2012 by AspDotNetDev
You want a negative lookahead or a negative lookbehind. Suppose you want to validate so that a phrase starts with "string" and ends with "bee", but does not contain "like". You could use this regular expression (which uses a negative lookahead):(?!.*like)^sting.*bee$The negative look ahead...
5 Sep 2012 by Mario Majčica
This should do:string a = @"If I had to live my life without you near me The days would all be empty The nights would seem so long With you I see forever oh so clearly I might have been in love before ...
2 Nov 2012 by fjdiewornncalwe
A really quick google search turned up this article: Search and Highlight Text in RichTextBox[^]. Maybe you can get a starting point from here.
20 Mar 2013 by Matthew Faithfull
At the lowest level you have the core C library functions like strcpy and memmove which deal with bytes and are both fast and unsafe in that there is little checking of anything, you have to get the parameters right to avoid crashing and you might have to manage things like NULL terminating...
20 Mar 2013 by H.Brydon
Solution #1 is good (but IMHO didn't answer all the questions).I have used both CString and std::string in my travels and my feelings are that std::string is newer than CString but in my observation not as robust. CString is Microsoft-only (so not portable, but if you move your code base to...
19 Apr 2013 by Sergey Alexandrovich Kryukov
What do you want really? To have the string "Record Not Found" "converted" to integer? With the value -1 or, perhaps, 666? :-)You explicitly assigned this value to a string in first line, why? you never use it.First of all, if you want to store integer in some cell, store integer, not a...
14 Sep 2013 by Sergey Alexandrovich Kryukov
Obviously, your bug is using inputString.Contains. It checks up is one string is a sub-string of another one, but your logic requires checking up is a single character is one of the vowels. Moreover, the calculation of the variable vow is completely pointless, and your call of Contains is just...
25 Feb 2014 by Sergey Alexandrovich Kryukov
Not true at all. This type is designed in much wiser way: there is no such constructor. These constructors do not exist: string(); string(string); the are simply never needed and having them would be even harmful.You mentioned the pool. It also does not work as you thought, and it is called...
26 Feb 2014 by CPallini
That is a pretty simple task: at each step you have to read the input file (line by line), collecting and concatenating the read lines until a stop condition is met. The stop condition is either a new start of line (the hiphen) or the end of file. Upon stop condition the collected lines are...
10 Mar 2014 by Mehdi Gholam
You need to create inverted indexes or use a component like lucene : https://lucenenet.apache.org/[^]or my article hOOt : hOOt - full text search engine[^]
10 Mar 2014 by Maciej Los
Please, read Sergey's comment to the question and follow below links:How to: Search Strings Using String Methods (C# Programming Guide)[^]How to: Search Strings Using Regular Expressions (C# Programming Guide)[^]
4 Aug 2014 by Thanks7872
See this :int month = DateTime.ParseExact("Aug 2014", "MMM yyyy", CultureInfo.InvariantCulture).Month;//month will be 8 in this caseAdd reference to System.GlobalizationRegards..
11 Sep 2014 by E.F. Nijboer
you could use String.Split. But if Young Adult is a single value it is not possible to detect that properly because every space would be a separator. The result would be: Youth Baby Young Adulthttp://msdn.microsoft.com/en-us/library/b873y76a%28v=vs.110%29.aspx[^]Good...
28 Apr 2015 by Sergey Alexandrovich Kryukov
There can be many ways to do this.One of the ways is: create a circular singly-linked list and remember the length of the string, say, N. This way, a pointer to any of the elements will give you the sequence of "rotated" letters if you pick next N elements. If you remember the original...
28 Apr 2015 by Andreas Gieriet
How about the following:char buf[BUFSIZE];strncpy(buf, "...", BUFSIZE-1);buf[BUFSIZE-1] = '\0';size_t len = length(buf);size_t i = 0;while(i
30 Oct 2015 by phil.o
I don't exactly see why you are trying to reinvent the wheel :)Localization framework already has got all what you need.The first wrong thing to do, IMHO, is to handle localizations directly by comparing to a ComboBox' text property. Ideally, you should handle the SelectedIndexChanged...
23 Feb 2016 by Patrice T
The output is correctYour mistake is that you sort a list of strings, not a list of numbers.so "6" fall between "54" and "77"a sort on strings is alphabetical.
14 Apr 2016 by Garth J Lancaster
I believe this Quote:[^$]is telling scanf to stop when you type the $ character.. if you did this [^\n]it would stop when you use the return key (ie, \n is NOT in the valid character class, so input stops)All this being said, scanf is usually used to get formatted input,...
1 Jun 2016 by OriginalGriff
String.Split isn't a Regex - it's just a basic string method that can't do anything too complex.Try:("[^"]*")|([^\s]+)as a regex - it should give you what you want as separate Group values.
30 Nov 2016 by CPallini
As suggested by enhzflep, it is the first parameter that doesn't fit.Try#include #include #include using namespace std;int main(){ vector v; v.push_back("A"); v.push_back("C"); vector::iterator it = v.begin() + 1; ...
25 Sep 2018 by Richard Deeming
I suspect there's something else going on with your code, or with your computer. Three seconds to filter an array of 8000 items is unbelievably slow. Using Benchmark.NET[^] to test the following code: public class LinqBenchmark { private readonly string[] _data; public LinqBenchmark()...
25 Sep 2018 by Eric Lynch
Really late to answer here, but I was curious what a slightly more rigorous exploration would yield. The method used to analyze/select your population, for such a small population (8K items), with such a simple filter (starts with 'a'), should be largely irrelevant. Even with a population of...
27 Apr 2020 by Garth J Lancaster
I think you need to be really careful about the names of your functions vs what you're asking for - your question with 'append' string, yet you've named your function 'prependToString', and have 'appendToString in the console write - they are two...
14 Aug 2023 by Andre Oosthuizen
I will use regular expressions to match the key-value pairs in your input string, others might disagree with me. :) I have created a fiddle for you at - Reading string values in C#[^] using System; using System.Text.RegularExpressions; public...
13 Sep 2010 by TheyCallMeMrJames
Should be pretty easy:decimal result = decimal.Parse("002056")/100m;The numeric types in .NET have Parse() and TryParse() methods to handle the conversion. If you're guaranteed the s9(6)99 format, you can likely get away with Parse().Use the m suffix to denote decimal types. Decimal...
1 Feb 2011 by Espen Harlinn
If you are doing text processing/parsing - you could consider usingGNU Bison[^]and flex[^]Remeber that you can use flex on its own, and it is reasonably fast :)Apart from that, I think you will find that nothing beats using pointers, and possibly reading files using ReadFile with...
2 Feb 2011 by M@dHatter
PHP Magic String Builder with Append Format.
27 Mar 2011 by Wendelius
Try changing the BodyEncoding[^] property.
20 Apr 2011 by Nish Nishant
No, you cannot cast a BSTR to a char*. Use ConvertBSTRToString. See http://msdn.microsoft.com/en-us/library/ewezf1f6(v=VS.100).aspx[^]
1 May 2011 by OriginalGriff
Yes.Simple...
1 May 2011 by Richard MacCutchan
Strings are preceded by a length byte as described here[^]. It's always best to read the documentation first.
29 Jun 2011 by Erich Ledesma
I rather like IEnumerable than IList, parameters should be as general as posible. I think it's really getting very fun up here. Here's my choice, just for strings.public static string Join(this IEnumerable parts, string separator){ if (! parts.Any()) return...
30 Oct 2011 by steveb
In UNICODE:CString str = L"Test";std::wstring ws(str);std::string s;s.assign(ws.begin(), ws.end());
16 Dec 2011 by Pascal Ganaye
A custom C# string implementation that stores its data in a UTF8 byte array.
3 Jan 2012 by OriginalGriff
Try:Dim source As String = "CHimaM"Dim extract As String = ""Dim start As Integer = source.IndexOf("C"C) + 1Dim [end] As Integer = source.IndexOf("M"C)If start >= 0 AndAlso [end] > start Then extract = source.Substring(start, [end] - start)End If
18 Jan 2012 by Namlak
string blah = string.Join(",", cities.Select(c=> c.Name));
18 Jan 2012 by Sergey Alexandrovich Kryukov
I think this would be easier:Define the Console methods you use with exact same name and signatures://[EDIT...]internal class UiConsole { internal UiConsole(TextBox sink) { this.Sink = sink; } internal string void WriteLine(string value) { /* this is easy */} ...
24 Jan 2012 by jocko3d
The TestConversion function is not valid. The line of code "data = data & Chr(n)" uses the Chr function to build a string of characters used for the test. The problem is that the Chr function is itself bound to a code page. Specifically, it will utilize the code page that is in use by the...
29 Jan 2012 by OriginalGriff
Try:Dim s As String = "123123452149856874"Console.WriteLine("{0} {1} {2} {3}", s.Substring(0, 8), s.Substring(8, 4), s.Substring(12, 4), s.Substring(16, 2))
17 Mar 2012 by ProEnggSoft
The FindString method of ListBox control returns the index of string in the items of the ListBox as shown below:int orangeIndex = listBox1.FindString("Orange");int appleIndex = listBox1.FindString("Apple");
26 Mar 2012 by Sergey Alexandrovich Kryukov
This could be done using the event onkeydown. However, I don't recommend doing it because you need to use event structure to solve this problem; and this creates a browser-compatibility problem. However, this problem can be worked around. Please...
2 May 2012 by Maciej Los
Sandeep Mewara was trying to tell you to use selecteditem object, not ListBox1.SelectedItems(LBitmCounter). In my example i replaced it with oItemFor Each oItem As [Object] In ListBox1.SelectedItems If oItem.ToString = "Text 1" Then Action 1 ElseIf oItem.ToString = "Text 2"...
13 Jun 2012 by SoMad
You will probably be able to do the string formatting as outlined in Solution 1, but in my experience, your basic approach is bound to cause major problems later on.Say you get to the point where your integer has the value 111024. Is that supposed to be interpreted as 11.1.024 or 1.11.024?...
14 Jun 2012 by JesseChisholm
FormatEx is a method that allows structuring formatting placeholders indirectly from arguments.
9 Jul 2012 by Matt T Heffron
This is an alternative for "Custom String FormatWith using Reflection"
9 Aug 2012 by wizardzz
I'm going to expand on what Kenneth said, adding that as a food is used, remove it from the list, so it is never repeated.
8 Sep 2012 by ridoy
http://www.java2s.com/Code/Java/Regular-Expressions/JavaRegularExpressionSplittext.htm[^]http://www.regular-expressions.info/java.html[^]http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation.shtml[^]http://forums.codeguru.com/showthread.php?292394-TIP-A-little-tutorial...
22 Sep 2012 by Wes Aday
You would use the match method, http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match[^]
5 Oct 2012 by Akinmade Bond
This worked for me.q = "15.Crank vs.Cams Bank 2"; // The variable to split. string s= q.Substring(txtsplit.Text.IndexOf('.')); //Get the text after the first '.' string[] v = s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); foreach...
5 Feb 2013 by SruthiR
You can use the code below:private static void GetCharCountInString() { const string strOriginal = "SSSEERRTADEEE"; string strNew = string.Empty; int index = 0; char[] chararray = strOriginal.ToCharArray(); for...
13 Feb 2013 by Richard MacCutchan
You could make use of the C-library string manipulation routines[^].
28 Feb 2013 by Jegan Thiyagesan
Hi,There are couple of things in your code,First: The string variable "State" is not initialized.Second: The conditions are between range 4 and 35, so if the sensor value was beyond this range the "Stat" variable will not be used, so you will get an unused variable warning.Have you...
15 Mar 2013 by Mike Meinz
The second parameter of String.Substring is length. I changed the 6 to a 3. string myString = TextBox1.Text.ToString();string substring = myString.Substring(0, 3);string substring2 = myString.Substring(3, 3);See String.Substring Method (Int32, Int32)[^]
23 Mar 2013 by Zoltán Zörgő
Compression in general is a little bit more complicated than that. But there is one, that might look like what you described, it is called run-length encoding[^].
24 Mar 2013 by Maciej Los
As Zoltan wrote, it's not so easy... especially when you do not provided enough information.Some usefull examples, you'll find here:A Simple String Compression Algorithm[^]Easy String Compression and Encryption[^]Interesting alternative is SMAZ[^] - simple compression library...
6 Apr 2013 by Anupam Singh
try to initialize filterQuery like string filterQuery="" or string filterQuery=string.Empty;
11 May 2013 by OriginalGriff
When I run your code with 99,999 byte strings (I cheated and read it from a file) I get "out of system memory" on the first run through GetSuffixes, so start by looking at that - and what do we find?Input string length: 99,999 bytes. "i" is 8,847, so it doesn't get near the end of the...
22 May 2013 by Thomas Daniels
Hi,Have a look here:Standard Numeric Format Strings[^]Custom Numeric Format Strings[^]How to: Pad a Number with Leading Zeros[^]String Format for Int [C#][^]
9 Sep 2013 by nv3
There are several bugs in your code. while(str[i]!='\0') { str[j]=str[i]; i=i+2; j++; }By incrementing i in steps of 2 you will run over the null terminator at the end. And that probably produces you segmentation fault. while(j { ...
9 Sep 2013 by H.Brydon
There may be other problems, but your first loop is defective. You check if the current index location is '\0' (fine) but increment i by 2. So if the NULL is in any odd location (1, 3, 5, 7...), your index will skip over it past the end of the string. The string you pass has 6 characters with...
18 Oct 2013 by Harshil_Raval
Hi,try this.int TextIndex = Array.FindIndex(inputstringarray, m => m == "Is");//replace "Is" with your other desired textHope it helps you.
18 Oct 2013 by BillWoodruff
I'd like to suggest you use the form of the String.Split method that removes "empty entries:"// defining the char[] used to Split in advance // can save memory if you are using it repeatedlyprivate char[] splitCharAry = new char[] { '\'' };string str =...
11 Nov 2013 by Thanks7872
First statement is incorrect. It is clear that 56 is being converted to Double so it should beDouble amount = Convert.ToDouble(56);And for the second one see this : Standard Numeric Format Strings[^]
11 Nov 2013 by Raje_
First line will throw compilation error, as you are trying to store a double value in string.string amount = Convert.ToDouble(56);this line should be : double amount = Convert.ToDouble(56);Result : 56.0and second line : string chkAmount = String.Format("{0:f}",...
19 Dec 2013 by Sergey Alexandrovich Kryukov
The code makes no sense. If you split by " ", you cannot replace " " simply because this character won't be found. You can identify the remaining terms by detecting the case when one starts with '(' and another ends with ')'. This is simple (I fail to understand why would you fail with such...
20 Dec 2013 by BillWoodruff
Here's one alternative using Split; this will handle the "position" entry having any amount of white-space, or being one continuous string:private string fName, lName, position;private string[] splitStr;private char[] splitChars = new char[] { ' ', '('};private void...