Click here to Skip to main content
15,891,708 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 Title

String 

11 May 2013 by Amogh Natu
Hi, I'm trying out a sample problem on strings wherein I take a string as input and find out the similarity of each of its suffix with itself. For two strings A and B, the similarity of the strings is the length of the longest prefix common to both strings. For example, the similarity of...
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...
11 May 2013 by debkumar@codeproject
Instead of storing all sub-strings (suffixes) in list object, calculate the sum of similarities for each suffix. I could not figure out your purpose of calculating the sum of similarity. You can look into KMP failure function if that helps.
12 Sep 2010 by Spenser723
I have a programs with thousands of variables. I need to perform complex operations on each of these variables that involves other variables. Some of the formulas that I will using will call methods that I have defined. So the string for z may be "x + y", but it might also be...
12 Sep 2010 by Abhinav S
Will operator overloading be of any help to you[^]?
13 Sep 2010 by Spenser723
Thanks for your response. Not sure that operator overloading would help in this case. That would be good if I wanted to perform standard operations on a new class object. In my case, what I want to do is the following:Let's assume that we have a program with the following...
13 Sep 2010 by aidin Tajadod
Hi,As I know there is no equivalent for eval (like vb6) in c#. but you can use system.CodeDom.Compiler namespace to create your own eval function. by using that you can compile your code on the fly and use it in your program.
28 Oct 2015 by Am Gayathri
Am trying to change the number format of a value in a data table. Am using String.Format("{0:n}", number) method to change the number format but it doesn't work.Below is my code, foreach (DataRow dr in datasetx.Tables[0].Rows) { ...
28 Oct 2015 by phil.o
This is a common mistake: you just counfound the decimal value (stored in the database) with its string representation.At no point you should store a formatted value in the database. The database has to hold the number; only when you display this number to the user you apply a format to it.
28 Oct 2015 by Anup Shetty
Have you called save changes method in your code?
29 Oct 2015 by PANKAJMAURYA
You need not to Call datasetx.Tables[0].AcceptChanges()like this method will write formatted string. protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); DataColumn dc = new DataColumn("total"); dt.Columns.Add(dc); ...
28 Oct 2015 by Krunal Rohit
Well, looking at your code:According to the MSDN[^]:AcceptChanges() Commits all the changes made to this table since the last time AcceptChanges was called.When AcceptChanges is called, any DataRow object still in edit mode successfully ends its edits. The DataRowState also changes: all...
18 Aug 2016 by Anti-Antidote
For some reason, the replace template from does not want to work for me. See example code below:#include #include #include using namespace std;int main() { string s = "Hello, world!"; replace(s.begin(), s.end(), "l", "i"); cout
18 Aug 2016 by Jochen Arndt
Your call replace(iterator, iterator, const char*, const char *) does not match the std::replace template:template void replace(_FIter, _FIter, const _Tp&, const _Tp&);_Tp is char here because the std::string iterators are pointing to char.So you must...
28 Aug 2022 by Apoorva 2022
Following is a date validation program. I'm trying to print the date in words. I got the 'str' object is not callable' error at this line --> av=date(day, month, year).strftime('%d %B %Y') But I did convert day, month, & year into integers...
28 Aug 2022 by OriginalGriff
Look at the error message: 'str' object is not callable' error at this line --> av=date(day, month, year).strftime('%d %B %Y') You are calling two functions here: date and strftime so one of those is wrong. Break the line in two and see if that...
28 Aug 2022 by Richard MacCutchan
I gave you the answer to this two days ago at Python date validation program - output query[^].
10 May 2018 by Member 13822063
Hey all, I'm a student and doing a practice for my exam. I will have to create a program that converts an input into binary. So far, I got the code working BUT I need my output to be in reverse order. I used [::-1] yet it doesn't seem to be doing it. Thanks! What I have tried: def...
10 May 2018 by Thomas Daniels
output is always just a one-letter string (because it's inside the loop), so reversing it just gives the same string. What you need to do, is reversing the whole string before printing it: def binary_converter(num): reverse = "" while num != 0: output = num % 2 # 0 or 1 ...
17 May 2010 by Sarang Date
Any string input can have these many possible states1) String is null2) String is empty3) String contains nothing but white space4) String has some contentTill now, .NET had static method for stringbool string.IsNullOrEmpty()which handled first two conditions for...
12 Aug 2010 by jfriedman
public static class StringExtensions { public static bool IsNullOrWhitespace(this string s) { if (null == s) return true; return string.IsNullOrEmpty(s.Trim()); } }
8 May 2018 by Ben Hall (failingfast.io)
It's worthwhile knowing the what, when and why to improving string comparison performance. In this article, I will explore one way, string interning.
29 Nov 2017 by Greek Varak
Madhan has been a given a problem by his brother Jayi .The problem is related to strings. Now he gives Madhan a long String S which consists of lowercase English Alphabets and wants him to tell the minimum size of substring such that all the substrings of that size in S have at least K...
25 Nov 2017 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action. Try it yourself, you may find it is...
29 Nov 2017 by Member 13549143
This may help public static int Consonant(String input1,int input2) { int consonant = 0; int total =-1; int count =0; String str=""; int tot_substring =0; for (count=1;count
7 Feb 2016 by User 12277010
I have an Array of strings. Each string contains multiple vars separated by a ",". I remember years ago when I did VB.NET there was a way to LINQ sort an array into corresponding vars, select which ones you need and use them however you like. For example: Dim facultyQuery = From member In...
6 Feb 2016 by Sascha Lefèvre
If you want to use the same approach, this is how you could do it in C#:// this declaration as a class member:static char[] splitChars = new char[] { ',' };// just some sample data:string[] rows = new string[] { "name2,1,2,3", "name1,3,4,5" };var query = from row in rows ...
6 Feb 2016 by OriginalGriff
Linq won't speed up the process that much - it's a loop as well, but it's a "deferred execution" loop that happens behind the scenes when the data is actually required instead of when the original query code is executed.And if the run time is "very bad" when loading your data into any...
22 Sep 2016 by Anti-Antidote
I am trying to create a menu using switch(). However, the compiler keeps throwing me errors like invalid conversion of 'const char*' to 'char' [-fpermissive]. Here is the code:void info::get_factorio_version(string* factorio_version){ bool loop = true; while(loop){ cout
22 Sep 2016 by Richard MacCutchan
You have declared select as int, but your case statements are using character constants. they should be like: switch(select){ case 1: *factorio_version = "0.14";Also you do not need block separators ({ and }) surrounding your case code.
29 Aug 2015 by Oliver S. Neven
Hello fellow programmers!I've made this whitespaceIndent method, for creating a indentation string out of whitespaces.My goal was to create a method, that replaces tabs.So fx, if I used tabs, this would be my output:Directory SizeC:/Games 126 MBC:/Program Files...
6 Aug 2020 by JacksonSteel
input: babad abbd output: ad bb expected: bab bb #include using namespace std; class Solution { public: string longestPalindrome(string s) { int maxlength=1; bool ispalindromic[1000][1000]={false}; ...
4 Aug 2020 by OriginalGriff
Compiling does not mean your code is right! :laugh: Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email...
6 Aug 2020 by Patrice T
Advice: Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes. #include using namespace std; class Solution { public: string...
22 May 2022 by Phoenix Liveon
A quick quest: We want the result looks like this; from aaa---bbb-ccc into aaa.bbb.ccc What I have tried: def objective = "aaa---bbb-ccc" objective.replace(/.*[-]+.*/, '.') How do we create a proper pattern of Regular expression in Groovy?
15 Apr 2022 by Patrice T
Did you tried this ? def objective = "aaa---bbb-ccc" objective.replace(/[-]+/, '.') Just a few interesting links to help building and debugging RegEx. Here is a link to RegEx documentation: perlre - perldoc.perl.org[^] Here is links to tools...
15 Apr 2022 by OriginalGriff
That's because you don't use the "non-hyphen" data in your replacement. Try this: (.*?)-+(.+?)-(.*) And this replacement string: $1.$2.$3
15 Apr 2022 by Phoenix Liveon
I found some answer and this is what its looks like we substitute method "replace" with "replaceALL"; def objective = "aaa---bbb-c" println( objective.replaceAll(/[-]+/, '.') )
27 Apr 2017 by Yaseen M
Solution: I changed the comparison to: if int(guess[i]) == number[i]: Full Program: import random def generateNumbers(): numbers = []; i = 0 while i
27 Apr 2017 by OriginalGriff
guess is not an [] - so it can;t be used with a subscript index. Try: if guess == number[i]:
27 Apr 2017 by Patrice T
Quote: That would defeat the purpose of the original code. Do the correction of solution 1, and use the debugger to see what your code is doing. Somewhere, your code is not doing what you expect. When you don't understand what your code is doing or why it does what it does, the answer is...
5 Feb 2019 by M Haikal Anatama
I have a string: string = "Yellow.car Red.Bag Blue.eyes" Is there a way to split the string on both periods and whitespaces, but only retain the periods inside the array? ['Yellow','.','Car','Red','.','Bag','Blue','.','Eyes'] A regex for string.split(regexp) would be preferable What I have...
28 Jan 2019 by Gerry Schmitz
Replace the periods with another token that includes a period; then split on the new token. e.g. if you want to split on "." and keep, then replace "." with "@." or ".@"; then split on "@".
28 Jan 2019 by OriginalGriff
In a Regex, dot '.' has a specific meaning: "any character". So a regex of "a.b" will match "aab", "abb", "acb", ... any character between an a and a b. So your regex: "(.|,)" is "either any character or a comma" - which amounts to "any character! You can escape it so that it becomes a literal:...
29 Jan 2019 by Patrice T
Quote: A regex for string.split(regexp) would be preferable Advice: study RegEx, there is more than 1 way to use it. Split is used to cut a string on separator and separator is lost. Match on the other side will make a list of every match in string. you just have to build a RegEx that will...
5 Feb 2019 by Maciej Los
Try this: Dim s As String = "Yellow.car Red.Bag Blue.eyes" s = s.Replace(".", " . ") Dim result = String.Join(",", s.Split(New String(){" "}, StringSplitOptions.RemoveEmptyEntries).Select(Function(w) String.Concat("'", w, "'"))) Result: 'Yellow','.','car','Red','.','Bag','Blue','.','eyes' As...
14 Jun 2012 by JesseChisholm
FormatEx is a method that allows structuring formatting placeholders indirectly from arguments.
16 Dec 2011 by Pascal Ganaye
A custom C# string implementation that stores its data in a UTF8 byte array.
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 Jan 2011 by martyn lucas
Hey people...I'm really not very good with c#, this is pretty much my first crack and I like it...but i'm pretty stuck and would really appreciate some help if you couldI'd like to get a string from textbox1, then on button click, send this text to textbox2 with 'x' after every other...
12 Jan 2011 by wizardzz
Hmm, try:textBox2.Text += (inputtext, i, 0);Thread.Sleep(200);textBox2.Text += (letterx.ToString());Thread.Sleep(200);
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 =...
12 Jan 2011 by martyn lucas
hey wizzard thanks for the reply...it comes up with a loads of errors, something to do with lamda conversion (??)and Hi mark. Basically for a small uni project i've built a bluetooth pager with an LCD controller. The long and skinny of it is a bt controller recieves a character sent from a...
10 Jun 2015 by Member 11758214
Hi guys, I have a string such as "x = 1, y = 2", and then I want to calculate the result of string "x + y" or "x * y", does any library can implement what I want??? Thanks very much!
10 Jun 2015 by Andy Lanng
Nope. You may find an API but I'd write one myself.Look at the below example of how to parse arithmetic strings using stacked operators There may be a API you can pull out of it:Math Parser .NET C#[^]
11 Jun 2015 by Stefan_Lang
This has nothing to do with math. Consequently you don't need a math library, but an expression parser: https://www.google.ch/search?q=experession+parser&ie=utf-8&oe=utf-8&gws_rd=cr&ei=D4J5VZmaHoKQsAGDh6eYBw#q=expression+parser+C%2B%2B[^]The first hit on that search already looks promising....
10 Oct 2011 by Brian C Hart
Okay, so I work for a "soda pop company," not really but to protect proprietary info, let's pretend I do. And I have an ASPX page that is passed a querystring likehttp://www.sodaforu.com/page.aspx?brand=cokeOK, so I want to place an "if" in the code so that if I don't pass one of our...
10 Oct 2011 by dasblinkenlight
Though not most efficient, long string method works perfectly well. I'd declare a constant set of strings, like this:private static readonly HashSet LegalNames = new HashSet(new[] { "coke", "pepsi", ...});and then use it to check the incoming queries, like this:if...
23 Feb 2012 by PIEBALDconsult
An Extension Method that is similar to String.StartsWith, but uses a StringComparer
24 Feb 2012 by Andreas Gieriet
This alternative is not substantially different, it simply splits the function into two:one for clippingone for comparingpublic static string ExtClipRight(this string a, int n){ return (n
28 Feb 2010 by Code-o-mat
Combo boxes under Windows have a "nice" feature of automatically selecting an item for the user when the user drops down the list of the combo box. This selection is based on partial string matching by the combo box, namely, it will select the first item in the list -if any- that begins with the...
28 May 2020 by kavinderrana121
I stuck at a problem SPOJ.com - Problem ABSYS[^] I executed my program on all the test cases ,I am getting correct answer. But still I am getting as "wrong answer" on spoj What I have tried: Breaking stream into strings storing them into vectors ,so we can say that our vector will have 5...
22 Jan 2019 by Arnav Varshney
I wouldn't be posting the entire code here, but I can surely help. This is how I would have had implemented the algorithm. First, take input in a string STR. Then break the string into 3 parts = NO1, NO2, ANS Now check in each string, if it contains the string "machula" Parse the string with...
22 Jan 2019 by Patrice T
Quote: But still I am getting as "wrong answer" on spoj Some site give logs of tests, any idea of the failing test ? Quote: Breaking stream into strings storing them into vectors ,so we can say that our vector will have 5 strings (numstring,+,numstring,=,numstring) Where have you seen that...
27 Mar 2011 by MarqW
Hi, I've a segment of code which combines the HTML signature from Outlook into an email settings (Code below).However, when the string contains accentuated characters (ie, é), the emails sent through the .NET Mail objects replace them with the "?" character. Is there anyway to retain the...
27 Mar 2011 by Wendelius
Try changing the BodyEncoding[^] property.
2 May 2020 by Pseudocode01
Write a function called charAt which accepts a string and an index (number) and returns the character at that index. The function should return an empty string if the number is greater than the length of the string. Can't use the built in...
28 Apr 2020 by OriginalGriff
Quote: Unfortunately no, keeps returning characters at an index or empty string. I've looked all over google too, this should be correct. So start by checking what you are passing to it, and how - use either JSFiddle or w3schools to build a...
2 May 2020 by Member 14819903
Here's the model solution function charAt(str, idx) { return idx
30 Dec 2021 by User 13045643
Hi, I have some issues with a button click event, practically, when pressed, should paste a string (this string is a combination of"any word" and a value, that it's a result of the text from a combobox, this one will change every time the index...
30 Dec 2021 by User 13045643
Sorry again guys, I think I found some solution, but if anyone have an optimal way to do it,I will mark that as solution, now my code work with these Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim...
31 Jan 2016 by bjay tiamsic
Hi! I am generating a text file that needs zero as a filler if the string does not meet the required length. The field that I need is the amount to I first convert it to string, but Im having a hard time getting the logic to meet my requirement.I have sample amount: 34340the string should...
31 Jan 2016 by Abhinav S
Try string strResult=strValue.PadRight(N, '0');
31 Jan 2016 by AnvisNet
long input = 34340;stringbuilder output = input.tostring; // somehow convert int to string or builder as per reqif(input100000 and input
31 Jan 2016 by BillWoodruff
private string PadZero(int source, int limit = 18){ StringBuilder sb = new StringBuilder(source.ToString().PadRight(limit, '0')); if (source
20 Nov 2015 by Miss R
Hi there.I am trying to add strings which are integers. I have 201404 as input and I need it to be converted to 201503 so the only way to do this is to increase the year (2014) by 1 and decrease the month 02 by 1. I have tried the below but the leading zero in the month does not seem to...
20 Nov 2015 by OriginalGriff
Change your DB.Don't store dates (even partial dates) as strings: always store them as DATE or DATETIME - that way, you can be sure they are all valid dates, and use the built in functions such as DATEPART and DATEADD. In you case, just set the day part to the first of teh month, and the time...
20 Nov 2015 by Wendell D H
I believe the problem is because you are treating integers like strings.03 is not a valid integer so it gets converted to 3.The rest of the convertions from int to varchar and back is the server helping you out a lot. However, with what you have you can get to the final value you are...
20 Nov 2015 by Patrice T
Why do you convert to string at all ?declare @YearMonth int =201404,set @YearMonth= @YearMonth + 99print @YearMonth
14 Apr 2016 by Member 12460800
I have letters in a string, I would like in result get all possible sets of those letters and convert them to numbers, each set should use all numbers, each number can occur only once in a set. numbers automatically should increment until 9. and output all possible combinations
14 Apr 2016 by xszaboj
I am not sure if this is what you need.But have a look on this problem:[^]and if this is the problem you are facingsolution is here:[^]it is in c#but general alghoritm is described here:Steinhaus Johnson Trotter permutation algorithm explained and implemented in Java...
28 Feb 2014 by dhiwatdg
I'm writing a code that identifies the highest-scoring local alignment between a substring X' of X and a substring Y' of Y that has at least one column in which a C from X' is aligned to a W from Y'. Example: if X=:HCEA and Y=:HWEA, then some of the local alignments with a column that aligns...
27 Jan 2015 by HiDensity
Class providing methods to count up a string using a definable character set.
27 Sep 2014 by Medise
I once came across a function in VB6 that received 3 parameters "Parameter","Match" and "Delimiter" that could extract information from a given string as follows:SiteAddress=XXXX;UID=XXXX;PWD=XXXXIn which SiteAddress, for example, is a parameter, ";" is the delimiter and "=" is the match....
27 Sep 2014 by Sergey Alexandrovich Kryukov
Why "custom functions"? Try something likeusing StringDictionary = System.Collections.Specialized.StringDictionary;// ...static StringDictionary ParseKeyValues(string source, char parameterDelimiter, char keyValueDelimiter) { StringDictionary result = new StringDictionary(); ...
11 Jun 2018 by Richard MacCutchan
See RegExr: Learn, Build, & Test RegEx[^].
11 Jun 2018 by Jochen Arndt
You will usually not find a solution that matches exactly your requirements. You have to know regular expressions (at least the basics) and do it yourself. When using the Regex.Replace Method (String, String) (System.Text.RegularExpressions)[^] you can use Substitutions in Regular Expressions |...
11 Jun 2018 by Maciej Los
You've got your answer here: C# string replace with regex[^]
9 Feb 2019 by Kohila G
Find the smallest window in a string containing all characters of another string - GeeksforGeeks[^] I can't wrap my head around this code. What does array inside an array mean? How can a character be an index to an array? What I have tried: // C++ program to find smallest window containing ...
9 Feb 2019 by Rick York
You have to think about what data each layer provides. The variable str, a string, is an array of characters. A character is just an integer of one byte. That means the value of str[j] is an integer that could range from 0 to 255, the range of one byte. That value is used to index into the...
9 Feb 2019 by Patrice T
Quote: How can a character be an index to an array? Learn about ASCII coding. Your don't understand what this code is doing, a tool can help you to, it the debugger ! Run your code on debugger step by step, inspect variables. The debugger is here to show you what your code is doing and your...
5 Jan 2021 by ynjay
I'm using Socket.IO to send some numbers and string to an array. However, it keeps converting everything to a String so I get an error message. Additionally I'm using ml.js for the models, the model logic is based of their random forest alorithm...
5 Jan 2021 by Patrice T
Quote: Array keeps returning as string I suspect that you have wrong assumption about how things works. Quote: into a double array msg = [[msg]] but it keeps converting it to I suspect that msg is a string and you embed it in a double array,...
21 Sep 2023 by OriginalGriff
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, this is part of your grades and it wouldn't be at all fair for us to do it all for you. So we need...
21 Sep 2023 by Richard MacCutchan
Lots of information at The Python Tutorial — Python 3.10.12 documentation[^]. Or if you really do not understand the question then ask your mentor.
21 Sep 2023 by li wilde
Given a pattern p to be a string, and the target string target, output the total number of patterns in the target string target p will only be number characters and target will only be lower case characters Runtime: 5s Test case: 2≤...
7 Oct 2023 by User 16071582
def compute_next(pattern: str) -> list: """ Compute the 'next' array for the KMP algorithm. Args: pattern (str): The pattern (substring) for which to compute the 'next' array. Returns: list: The computed 'next'...
27 Dec 2015 by PeMaCN
I'm trying to print in PDF two columns of information that contain some strings that the user inputs. This is my code so far:string s = ""; s = s + string.Format("{0,-60}", "Name: " + name);s = s +...
27 Dec 2015 by Richard MacCutchan
If you are using a fixed width font, then you just need to use the length of each string to calculate the number of spaces required. If you are using variable width fonts than you need to use graphics draw methods to position each field at a specific point on the page.