Menu
  • HOME
  • TAGS

Regex to split string by whitespace OR minus signs in C#

regex,string,split

Just split according to the below regex. @"\s+|(?<!\s)(?=-)" DEMO ie, string[] split = Regex.Split(input_str, @"\s+|(?<!\s)(?=-)"); ...

Split string in macro

c++,string,split,macros

You can just change your macros so that it will accept two parameters: the namespace name and the class name. Something like #define BASICTYPE_TRAITS(namespaceName, className) \ template <> \ struct DDSTraits<namespaceName::className> \ { \ using TypeSupportImpl = namespaceName::className##Impl; \ using TypeSupport_var = namespaceName::className##TypeSupport; \ }; template <typename T> struct BASICTYPE_TRAITS...

How to match words in 2 list against another string of words without sub-string matching in Python?

python,regex,string,loops,twitter

Store slangNames and riskNames as sets, split the strings and check if any of the words appear in both sets slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"]) riskNames = set(["enough", "pop", "final", "stress", "trade"]) d = {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"} for...

Display only values containing specific word in array

php,arrays,json,string,if-statement

You can use substr_count() <?php foreach($soeg_decoded as $key => $val){ $value = $val["Value"]; $seotitle = $val["SEOTitle"]; $text = $val["Text"]; if(substr_count($value, $searchText) || substr_count($seotitle, $searchText) || substr_count($text, $searchText)){ echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text . '</td></tr>'; } } ?> Read more at: http://php.net/manual/en/function.substr-count.php ...

Create a new loop without quotation marks

python,string,for-loop

Your item is a tuple: >>> item = ('Highest quarter rate is between', '1/1/15', 'and', '1/3/15', 'with rate:', 924.9966666666666) The string version of a tuple is its representation, for example: >>> str(item) "('Highest quarter rate is between', '1/1/15', 'and', '1/3/15', 'with rate:', 924.9966666666666)" Instead, you want to convert each element...

byte array to string and inverse : recoverded byte array is NOT match to original byte array in Java

java,string,bytearray

You cannot convert an arbitrary sequence of bytes to String and expect the reverse conversion to work. You will need to use an encoding like Base64 to preserve an arbitrary sequence of bytes. (This is available from several places -- built into Java 8, and also available from Guava and...

C# IEnumerable and string[]

c#,arrays,string,split,ienumerable

You have to use ToArray() method: string[] result = "bobjoecat".SplitBy(3).ToArray(); // [bob, joe, cat] You can implicitly convert Array to IEnumerable but cannot do it vice versa. ...

Combine every 2 elements in an odd-sized array, leaving the last element on its own (Java)

java,arrays,string

Actually you are making logic complicated, which is not required. What you said could just be written into codes like this : ArrayList<String> encryptedBinaryList = new ArrayList<>(); String temp = ""; for (int i = 0; i < ciphertextVals.length; i++) { if (i % 2 == 0) { temp =...

Create string without repeating the same element jn the string (Matlab)

string,matlab

Use unique with the 'stable'option: str = 'FDFACCFFFBDCGGHBBCFGE'; result = unique(str, 'stable'); If you want something more manual: use bsxfun to build a logical index of the elements that haven't appeared (~any(...)) before (triu(..., 1)): result = str(~any(triu(bsxfun(@eq, str, str.'), 1))); ...

Decremented value called in the recursion in Haskell

string,function,haskell,recursion,parameters

Yes, once you call again f with a new value of n, it has no way to reference the old value of n unless you pass it explicitly. One way to do it is to have an internal recursive function with its width parameter, as you have, but that can...

How to use Split() method in Android

java,android,string,list,split

I suggest you to use Pattern and Matcher classes. The below regex will capture the text present inside curly braces and then it would add them to the list variable. String myString = "A=myPage{a1,b1,c1};B=myPage{a2,b2,c2};C=myPage{a3,b3,c3};"; List<String> list = new ArrayList<String>(); Matcher m = Pattern.compile("\\{([^{}]*)\\}").matcher(myString); while(m.find()) { list.add(m.group(1)); } System.out.println(list); ...

saving base64 decoded string into a zip file

java,string,zip,base64,decode

Don't create a string from your byte array (String decodedString = new String(byteArray);), to then use an OutputStreamWriter to write the string, because then you are running the risk of introducing encoding issues that are platform dependent. Just use FileOutputStream to write out the byte array (byte[] byteArray) directly to...

SCALA: change the separator in Array

arrays,string,scala,delimiter

Your question is unclear, but I'll take a shot. To go from: val x = Array("a","x,y","b") to "a:x,y:b" You can use mkString: x.mkString(":") ...

python splitting string twice

python,string,split,pair

You can use a list comprehension to do both splits at once and return a list of lists: >>> a = '{1;5}{2;7}{3;9}{4;8}' >>> [item.split(';') for item in a[1:-1].split('}{')] [['1', '5'], ['2', '7'], ['3', '9'], ['4', '8']] ...

Zip with tuples and list

python,string,list,zip,tuples

To correct your code, here is the fix: def twoStrings(string1,string2): return zip(string1,string2) ...

Match part of string with part of other string

php,regex,string,preg-match

Use something like this (split the searched word into two parts and look for a match thas has characters between those two parts): $products = array( 'fruit applebag', 'pinapple', 'carrots', 'bananas', 'coconut oil', 'cabbage', ); $s = 'fruitbag'; $results = array(); foreach( $products as $index => $product ) { for($i=1;$i<strlen($s);$i++){...

Remove Strings with same characters in a String Array

java,arrays,string

TreeSet allows us to give a comparator. See whether this helps. package empty; import java.util.Arrays; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class RemoveDuplicateStrings { public static void main(String[] args) { String[] name1 = {"amy", "jose", "jeremy", "alice", "patrick"}; String[] name2 = {"alan", "may", "jeremy", "helen", "alexi"}; String[] name3 =...

Have an if statement look ONLY at the first word in a string [duplicate]

c++,string,if-statement,vector

The first line places string beginning with 'abc' at the end, and the second erases them from the vector. auto end_it = std::remove_if(myvec.begin(), myvec.end(), [](const string &str){ return str.find("abc") == 0 ;}) ; myvec.erase(end_it, myvec.end()) ; ...

Characters and Strings in Swift

ios,string,swift,unicode,character

When a type isn't specified, Swift will create a String instance out of a string literal when creating a variable or constant, no matter the length. Since Strings are so prevalent in Swift and Cocoa/Foundation methods, you should just use that unless you have a specific need for a Character—otherwise...

What is the usage of adding an empty string in a javascript statement

javascript,string,concatenation

Type Casting. It converts the type to string If variable current.condition_field is not of string type, by adding '' at the end of it converts it to string. var field = current.condition_field + ''; So, field is always string. Thanks to @KJPrice: This is especially useful when you want to...

String manipulation with batch scripting

windows,string,batch-file,space

your line set temp=%%c is the reason. There are spaces at the end. Use this syntax to avoid unintended spaces: set "temp=%%c" ...

Typecasting int to char, then search array

c,arrays,string,casting,int

Use cast_number/*char*/ = (char) help_variable_remove_pv + '0'/*int*/; instead of cast_number/*char*/ = (char) help_variable_remove_pv/*int*/; A character and an integer somewhat are different. This means that '0'(character 0) and integer 0 aren't equal. You'll have to add 48 (ASCII value of '0') to 0 to get the integer value of '0'. See...

Concatenation of strings array issues in Python: Str(ArrayOfString[1])+“ ”+Str(ArrayOfString[2]) doesn't seem to work

string,python-2.7,concatenation,slice,string-length

Just change your first attempt to following: if len(str(row[1])) >= 16: row[2] = str(row[1])+" "+str(row[2]) row[1] = str(row[1][0:16]) My answer is freely adapted from comment by @phylogenesis. Update: The above answer wont work because row is a tuple and hence it is immutable. You will need to assign the values...

Easiest way to Add lines wrong a .txt file to a list

c#,string,list,streamreader

I want to put all the lines of the file in a list Then you are working currently working too hard. You can use File.ReadLines, which yields an IEnumerable<string> and pass that into a List<string>: var allTextLines = new List<string>(File.ReadLines(path)); ...

How to declare multiple local variables as empty string of String^ in VC++

c++,string,c++-cli

It isn't fundamentally different from C#: String ^a1, ^a2, ^a3, ^a4; a1 = a2 = a3 = a4 = String::Empty; // or a1 = a2 = a3 = a4 = " "; Do keep in mind that String is a reference type, there is no point in using gcnew for...

bash: How can I assemble the string: `“filename=output_0.csv”`

string,bash,concatenation

An answer was posted, which I thought I had accepted already, but for some reason it has been deleted, possibly because it didn't quite answer the question. I posted another similar question, and the answer to that helped me also answer this question. You can find said question and answer...

How to highlight all the occurrence of a particular string in a web page?

java,html,string,swing

To solve my issue, I first added to my swing app a class that implements a swing browser. I just copied the code from Oracle: http://docs.oracle.com/javafx/2/swing/SimpleSwingBrowser.java.htm Then I put a call for this class into a listener: .addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { String urlto = jTextField8.getText(); String...

Concatenate appended strings and remove last character

javascript,jquery,string,concat

The reason it wasnt working before is because to access the text you need to use text() and you need to do it after the iterations p.text(p.text().slice(0, -2)); //notice -2 because you have an additional space ', ' $(document).ready(function() { var item = $('ul li'); var p = $('p'); item.each(function()...

Concatenating strings using foreach

php,string

The error is here: if(in_array($row, $char_type)) { You're actually looking for if the key exists, not whether the array contains that string - you need to use isset: if(is_array($type)) { foreach($type as $row) { if(isset($char_type[$row]) { $strtester .= $char_type[$row]; } } } print_r($strtester); exit(); ...

Convert each letter of string into ascii values - java

java,string,ascii

Well adding two Strings is simply concatenation using the + operator: //first and second should be declared as String. String both = first + second; Look here to see how to remove duplicate characters from a String. Lastly, the ascii value of a character is just the int value of...

.cpp:23: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’

c++,string

Use stoi, it's the modern C++ version of C's atoi. Update: Since the original answer text above the question was amended with the following error message: ‘stoi’ was not declared in this scope Assuming this error was produced by g++ (which uses that wording), this can have two different causes:...

search string in textfile [on hold]

c++,c,string,text

If using C/C++ is not mandatory, then grep is probably your friend : grep "size [0-9]*" -o yourfile.txt > all_sizes.txt And if you only need the 50 first results, head it is : head -n 50 all_sizes > result.txt (Now, this assumes you're using some kind of Unix, or OS...

strip_tags() on MySQLi Query and PHP Function [closed]

php,mysql,string,function,mysqli

strilp_tags() is definitely somewhere in your code to throw the error. Try posting all the codes involved so we can find out where your problem is coming from.

Split by a word (case insensitive)

python,regex,string,split

You can use the re.split function with the re.IGNORECASE flag (or re.I for short): >>> import re >>> test = "hI MY NAME iS FoO bar" >>> re.split("foo", test, flags=re.IGNORECASE) ['hI MY NAME iS ', ' bar'] >>> ...

Remove quotes to use result as dataset name

r,string

You can get the values with get or mget (for multiple objects) lst <- mget(myvector) lapply(seq_along(lst), function(i) write.csv(lst[[i]], file=paste(myvector[i], '.csv', sep='')) ...

Converting strings to arrays c#

c#,arrays,string

This should give you an idea on how to work with the strings. Private Sub SplitStrings(s As String) Dim lines() As String = Split(s, "____") For Each line As String In lines Dim perLineTokens() As String = line.Split("___") Next End Sub ...

REGEX python find previous string

python,regex,string

Updated: This will check for the existence of a sentence followed by special characters. It returns false if there are no special characters, and your original sentence is in capture group 1. Updated Regex101 Example r"(.*[\w])([^\w]+)" Alternatively (without a second capture group): Regex101 Example - no second capture group r"(.*[\w])(?:[^\w]+)"...

I need to make sure that only certain characters are in a list?

python,regex,string,list,python-2.7

With such a small range you could just iterate the move_order and check if each element exists in the allowed moves def start(): move_order=[c for c in raw_input("Enter your moves: ")] moves = ['A','D','S','C','H'] for c in move_order: if c not in moves: print "That's not a proper move!" return...

calling string as variable in python

python,string,variables

It's probably better to use a dictionary here. Define one with segments = {}. Then you can create a SignalParam by keying into your dictionary with your segment number: segments[segment_number] = SignalParam() and use the object like this: segments[segment_number].frequency = 33 ...

java : create string objects using a delimeter

java,string

Use the method String.split(regex): String input = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0"; String[] parts = input.split(";"); for (String part : parts) { System.out.println(part); } ...

How do I isolate the text between 2 delimiters on the left and 7 delimiters on the right in Python?

python,regex,string,split

You can use python's built-in csv module to do this. j = next(csv.reader([string])); Now j is each item delimited by a , and will include commas if the value is wrapped in ". See j[2]....

Extracting Substring from File Name

string,awk,substring,extract,cut

I would use sed: $ echo "asdfasd_d20150616asdasd" | sed -r 's/^.*_d(.{8}).*$/\1/' 20150616 This gets a string and removes everything up to _d. Then, catches the following 8 characters and prints them back. sed -r is used to be able to catch groups with just () instead of \(\). ^.*_d(.{8}).*$ ^...

Program to reverse a string in C without declaring a char[]

c,string,pointers,char

Important: scanf(" %s", name); has no bounds checking on the input. If someone enters more than 255 characters into your program, it may give undefined behaviour. Now, you have the char array you have the count (number of char in the array), why do you need to bother doing stuffs...

Comparing cell contents against string in Excel

string,excel,if-statement,comparison

We need an Array formula. In G2 enter: =NOT(ISERROR(MATCH(1,--EXACT(F$2:F$7,E2),0))) and copy down. Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key. Note: The curly brackets that appear in the Formula Bar should not be typed....

jQuery / Regex: How to compare string against several substrings

jquery,regex,string,substring,substr

You could convert this to a slightly more maintainable format, without getting into regular expressions. This is one way to use an array to accomplish your goal: // Super-quick one-liner: var str = '2042038423408'; var matchCount = $.grep(['12', '23', '34', '45', '56', '67', '78', '89', '90', '01'], function(num, i) {...

Swift: String contains Character?

string,swift,character

You can use the free-standing find function, like this: let s = "hello" if (find(s, "x") != nil) { println("Found X") } if (find(s, "l") != nil) { println("Found "L) } ...

Regex pattern in Python to search for text block inside a file

python,regex,string

The difficult bit here is to manage opening and closing curly brackets. If you have potentially unlimited depth for nesting the brackets, then I don't think you can do it with regular expressions, because it would be a recursive pattern. In that case you would need a parser, keeping track...

Escape html & non-ascii chars with javascript

javascript,html,string,escaping,non-ascii-chars

I found what you are looking for here For the purpose of your needs you have to use htmlEncode function. They define a number of other useful functions within the object: HTML2Numerical: Converts HTML entities to their numerical equivalents. NumericalToHTML: Converts numerical entities to their HTML equivalents. numEncode: Numerically encodes...

When trying to include “ in a String, using \” works but the \ is included too

xcode,string,swift,string-formatting

As you can see in the documentation: String literals can include the following special characters: The escaped special characters \0 (null character), \ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote) (snip) let wiseWords = "\"Imagination is more important than knowledge\"...

Regex to remove `.` from a sub-string enclosed in square brackets

c#,.net,regex,string,replace

To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

How can I convert an int to a string in C++11 without using to_string or stoi?

c++,string,c++11,gcc

Its not the fastest method but you can do this: #include <string> #include <sstream> #include <iostream> template<typename ValueType> std::string stringulate(ValueType v) { std::ostringstream oss; oss << v; return oss.str(); } int main() { std::cout << ("string value: " + stringulate(5.98)) << '\n'; } ...

Java, cut off array line before charactern nr. X

java,arrays,string,break

Assuming it is an String array, below code should do for (int i = 0; i < stringArrAC.length; i++) { stringArrAC[i] = stringArrAC[i].substring(64); } ...

Android String if-statement

java,android,string

Correct me if I'm wrong. If you're saying that your code looks like this: new Thread(new Runnable() { public void run() { // thread code if (ready.equals("yes")) { // handler code } // more thread code }).start(); // later on... ready = "yes"; And you're asking why ready = "yes"...

How to remove diacritics (accents) from a string?

string,dart,diacritics,unaccent

Not throughougly tested but seems to work void main() { var paragraph = "L'avantage d'utiliser le lorem ipsum est bien évidemment de pouvoir créer des maquettes ou de remplir un site internet de contenus qui présentent un rendu s'approchant un maximum du rendu final. \n Par défaut lorem ipsum ne...

How to find if exist an uppercase character in string?

string,axapta,x++,dynamics-ax-2012,uppercase

The code below tests if a string is one character or more and afterwards finds all the uppercase characters. Numbers are ignored since they cannot be uppercase. static void findCapitalLetters(Args _args) { str testStr = "!#dE2"; int i; int stringLenght = strLen(testStr); str character; //Find out if a string is...

Adding and Subtracting numbers from a String

java,regex,string,delimiter

Just put +, - inside a character class. sc1.useDelimiter("\\s*[-+]\\s*"); ...

How to extract first letters of dashed separated words in a bash variable?

linux,string,bash,shell,variables

This isn't the shortest method, but it doesn't require any external processes. IFS=- read -a words <<< $MY_TEXT for word in "${words[@]}"; do MY_INITIALS+=${word:0:1}; done ...

free causing different results from malloc

c,string,malloc,free

Every time you are creating your string, you are not appending a null terminator, which causes the error. So change this: for(j=0; j<rem_len; j++) { if(j != i) { remaining_for_next[index_4_next] = remaining[j]; index_4_next++; } } to this: for(j=0; j<rem_len; j++) { if(j != i) { remaining_for_next[index_4_next] = remaining[j]; index_4_next++; }...

Sql string search

sql,string,search,select

Not sure what you're trying to do with the NULL there, but basically you if you want to find a capital that contains the name of the country, the usage of the like operator is definitely in order. Just slap a couple of wildcards (%) around it, and you should...

Stopping condition on a recursive function - Haskell

string,function,haskell,if-statement,recursion

Your code doesn't handle the case where a line is shorter than the maximum length. This is somewhat obscured by another bug: n is decremented until a whitespace is found, and then f is called recursively passing this decremented value of n, effectively limiting all subsequent lines to the length...

More convenient way to work with strings in winapi calls

string,winapi,rust

In your situation, you always want a maximum of 255 bytes, so you can use an array instead of a vector. This reduces the entire boilerplate to a mem::uninitialized() call, an as_mut_ptr() call and a slicing operation. unsafe { let mut v: [u16; 255] = mem::uninitialized(); let read_len = user32::GetWindowTextW(...

Memory consumption when chaining string methods

c#,string,immutability,method-chaining

Is it true that when you chain string functions, every function instantiates a new string? In general, yes. Every function that returns a modified string does so by creating a new string object that contains the full new string which is stored separately from the original string. There are...

strcmp performance in C

c,string,algorithm,data-structures

Yes, this is in O(n) in the average and worst case, where n is the length of the shorter of both given strings. You could also express that as O(min(m,n)) with m and n being the lengths of both strings, respectively. But no, O(n) doesn't mean that it needs exactly...

How to avoid the StringIndexOutOfBoundsException if a substring is not in my original String?

java,string,substring,indexof

You can do a preliminary check to make sure the tags you are looking for are present in the String : String idCodice = null; int startTag = cessionarioCommittente.indexOf("<IdCodice>"); int endTag = cessionarioCommittente.indexOf("</IdCodice>"); if (startTag >= 0 && endTag > startTag) { idCodice = cessionarioCommittente.substring(startTag + 10, endTag); } By...

(VBA Excel) Extract Text and related Letter from String and output result

regex,string,excel-vba,character,number-formatting

This is how I'd do it - Sub test() Dim myFile As String myFile = "C:\reformatted.txt" Open myFile For Output As #1 Dim iPar As Integer Dim sChar As String Dim sBlank As Long Dim cont As Boolean Dim mystring As String For Each c In Range("A:A") If c <>...

Freeing array of dynamic strings / lines in C

c,string,sorting,malloc,free

There are multiple problems in your code: function getline: the string in the line buffer is not properly '\0' terminated at the end of the do / while loop. It does not free the line buffer upon end of file, hence memory leak. It does not return a partial line...

How to use the contents of a text file(tab delimited format) to rename files in a folder?

c,windows,string,rename

You could use powershell if you want. I think this would work. $names = (gc core.txt) $idx = 1 gci core*.jpg | %{ $newname = $names[$idx++].trim().split("`t")[0] + ".jpg" ren $_ $newname } Edit: It's this .trim().split("`t")[0] part that splits each line of core.txt on tabs and returns the first element....

Python str.format() — passing in list, outputting list

python,string,string-formatting

You cannot get your output as shown using a single format. You can use a list-comp >>> listex = range(0, 101, 25) >>> ["https://thisisan{}example.com".format(i) for i in listex] ['https://thisisan0example.com', 'https://thisisan25example.com', 'https://thisisan50example.com', 'https://thisisan75example.com', 'https://thisisan100example.com'] You can use map here (if you are using Py3, wrap a list call), >>> map("https://thisisan{}example.com".format,listex) ['https://thisisan0example.com',...

C++ & Qt: Random string from an array area

c++,arrays,string,qt,random

You should use the random header. #include <random> std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for...

Regex pass dynamic values with boundry

c#,regex,string,boundary

Your first regular expression has a black slash followed by the letter b because of that @. The second one has the character that represents backspace. Just put an @ in front string bound = @"\b"; ...

jQuery counter insert commas to break up string

javascript,jquery,string,counter

in your .html() function, change counter to counter.toLocaleString() like this: var counter=22000000000; if(typeof(localStorage.getItem('counts'))!='object') { counter=parseInt(localStorage.getItem('counts')); } $(".count").html(counter.toLocaleString()); setInterval(function () { $(".count").html(counter.toLocaleString()); ++counter; localStorage.setItem('counts',counter); }, 18000); ...

Replace multiple numbers with other numbers in a string using REGEX c#

c#,regex,string

As you mentioned you need to capture and replace the max value, I will take into account only that non-capturing group. The special character \s+ is used to indicate one or more white spaces. Regex reg = new Regex("(Movement\s+display_name=\"Movement\"\s+type=\".*\" .*min=\".*\"\s+max=\").*(\")"); Now you can replace the not captured group, I mean...

Translating a character array into a integer string in C++

c++,arrays,string

If you want a sequence of int, then use a vector<int>. Using the key_char string, the values of the chars in it will serve as the initial value of the ints. std::vector<int> key_num(key_char.begin(), key_char.end()); Then, iterate over each character of key_num and convert it to the equivalent int value for...

Given length L find the shortest string formed only of as & bs >= L such that adding some character (Either a or b) doesn't produce a new palindrome

string,algorithm,palindrome

Here are my results so far: L=1-7: "aabbaba" -> "aabbabaa" (or the mirror, confirming your result) L=8: "aaabbaba" -> "aaabbabaa" (or the mirror) L=9: "aaaabbbaba" -> "aaaabbbabaa" (or the mirror) All futher L can be solved just by prefixing an additional a to the starting string....

String replace method is not working in android studio

java,android,string

You're trying to replace "From: " but you only added "From " (without the :).

How to remove characters before and including an underscore?

linux,string,bash,unix,awk

Using Parameter Expansion: $ var="fooo_barrrr" $ echo ${var#*_} barrrr To change the var itself, var=${var#*_}. Note this removes up to the first _: $ var="fooo_barrr_r" $ echo ${var#*_} barrr_r If you wanted to remove up to the last one, you would need to use ## instead: $ var="fooo_barrr_r" $ echo...

Split by a comma that is not inside parentheses, skipping anything inside them

java,regex,string,split

Could not figure out a regex solution, but here's a non-regex solution. It involves parsing numbers (not in curly braces) before each comma (unless its the last number in the string) and parsing strings (in curly braces) until the closing curly brace of the group is found. If regex solution...

Find second to last word in multi-lined string array

java,string

Java 8 makes this simpler. Count the occurrences of the next to last word with a HashMap, then use streams to sort the HashMap in descending order and grab the top three values. public static void main(String[] args) throws Exception { List<String> lines = new ArrayList() { { add("abcd i");...

C++ error: deduced conflicting types for parameter 'T' string vs const char *

c++,string,templates,c++11,char

Well, std::string and const char* (<- this is what "pear" decays to when calling the function) are two different types you both want to deduce T from, just as the compiler says. To fix the issue, call the function with the correct type: searchInDequeFor(myDeque,std::string("pear")); ...

char* string substract function throws exception

c++,arrays,string,char

The first obvious mistake you're doing here is this: char* temp = new char[255]; temp = this->c_str(); You allocate memory then you're copying the value of a pointer. So first you're getting a memory leak and second depending on your implementation of c_str() you are copying the address of something...

Giving a string variable as a filename in matlab

string,matlab,filenames

You would need to change your back slashes \ to forward slashes /, otherwise some \ followed by a letter may be commands in the sprintffunction, like for example \N or \a. See sprintf documentation in the formatSpecarea for more information. original_image=imread(sprintf('D:/Academics/New folder/CUB_200_2011/images/%s', C{1}{2*(image_count)})); ...

Matching string inside file and returning result

regex,string,bash,shell,grep

Using sqlite3 from bash on OS X seems fairly straightforward (I'm no expert at this, by the way). You will need to find out which table you need. You can do this with an interactive session. I'll show you with the database you suggested: /Users/fredbloggs> sqlite3 ~/Library/Application\ Support/Dock/desktoppicture.db SQLite version...

Javascript Regex to find any number (greater than 0) between two colons

javascript,regex,string

You can use this regex: /:(?!0*:)\d+:/ (?!0*:) is a negative lookahead that will fail the match if only 0s are found between colons. RegEx Demo...

How To Check Value Of String

javascript,css,string,numeric

document.GetElementById("tombolco").style = "display:block"; That's not the right way. This is document.getElementById("tombolco").style.display = 'block'; Also note that it is getElementById, not with a capital G. Same with 'none',Rest of your code is fine. Fiddle...

Android Studio plugin for capture Strings

android,string,android-studio

I'm not exactly sure what you are asking, but if you are wondering how you can find all of your hardcoded strings, you can find them through Android Lint. In android studio go to Analyze -> Inspect Code. Then in the results expand Android Lint. Hardcoded text will be one...

String parsing with batch scripting

windows,string,parsing,batch-file,xml-parsing

This should work: @ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION FOR /F "tokens=*" %%a in (pictures.xml) DO ( SET b=%%a SET b=!b:"=+! FOR /F "delims=+ tokens=2" %%c in ("!b!") DO ( ECHO %%c ) ) This will output only something.jpg. Here the expülanation: First we split the file into lines. Now we want...

How to call function on every value of String List and change it?

c#,string,foreach

Instead of foreach try with Select, ForEach iterate over all the list but is a void, it doesn't return any result. But with select you can do a projection to return processed values. s.Tags = s.Tags.Select(t => TagCleaner.foo(t)).ToList(); ...

C++11 Allocation Requirement on Strings

c++,string,c++11,memory,standards

Section 21.4.1.5 of the 2011 standard states: The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size(). The two...

Scala: Convert a csv string to Array

arrays,string,scala,split,scala-collections

Use split with -1 argument. string.split(",",-1) This behavior comes from Java (since Scala uses Java Strings). Here is the documentation directly out of Javadoc. ...

Cannot Properly Print Contents of Vector

c++,arrays,string,vector,segmentation-fault

You said: I have some C++ code where I'm taking input from a user, adding it to a vector splitting the string by delimiter, and for debugging purposes, printing the vector's contents. And your code does: while (true) { //Prints current working directory cout<<cCurrentPath<<": "; /// /// This line of...

A beginner questions about printf, java

java,string,printf

I'm sad that this question hasn't been answered, and upon that, I can't upvote it from it's -8 cause I don't have enough reputation. It seems downvoting is getting too unwarranted here. OP is just looking for an answer, which can be answered here and found online, he has tried...

Scala string replacement of entire words that comply with a pattern

string,scala,scala-collections,scala-string

You can use the \bth\w* pattern to look for words that begin with th followed by other word characters, and then replace all matches with "123" scala> "this is the example, that we think of, anne hathaway".replaceAll("\\bth\\w*", "123") res0: String = 123 is 123 example, 123 we 123 of, anne...

Get the title of a file into a string WITHOUT the extension

php,string

Have a look at basename. It does exactly what you want.