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}).*$ ^...
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...
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]....
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 <>...
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...
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='')) ...
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:...
Just split according to the below regex. @"\s+|(?<!\s)(?=-)" DEMO ie, string[] split = Regex.Split(input_str, @"\s+|(?<!\s)(?=-)"); ...
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(...
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(); ...
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...
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...
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...
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...
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");...
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); ...
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\"...
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...
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...
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 ...
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()) ; ...
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"...
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)); ...
Assuming it is an String array, below code should do for (int i = 0; i < stringArrAC.length; i++) { stringArrAC[i] = stringArrAC[i].substring(64); } ...
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 ...
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" ...
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...
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...
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...
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...
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...
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"; ...
Just put +, - inside a character class. sc1.useDelimiter("\\s*[-+]\\s*"); ...
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...
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...
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...
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...
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...
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) } ...
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...
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]+)"...
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...
The simplest, recommended way is to just take the argument as a Python string: def myfunc(str mystr): ...
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...
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...
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']] ...
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))); ...
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 ...
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...
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()...
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...
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)})); ...
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...
Use str.index and EAFP try: if string.index("Long") < string.index("Short"): length = "Long" else: length = "Short" except ValueError: if "Long" in string: length = "Long" elif "Short" in string: length = "Short" else: print ("Long and Short not in string") ...
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...
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...
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")); ...
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...
I am not 100 % sure, but I think you might need to use VBA for this. You could try to create the following custom function: Create named ranges properties and problems in your sheet. Click ALT+F11 to open VBA editor. Press Insert --> Module Write code ' Function ConcatIF(Property...
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',...
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 =...
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...
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...
Have a look at basename. It does exactly what you want.
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'] >>> ...
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...
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....
You're trying to replace "From: " but you only added "From " (without the :).
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....
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...
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); ...
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...
javascript,jquery,string,wordpress
No need for string manip, use the removeClass method: $('.icon-option i.selected').removeClass("selected"); If you then also need the string of the class names you can expand to: $('.icon-option i.selected').removeClass("selected").attr("class"); ...
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++){...
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...
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); } ...
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) {...
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(":") ...
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...
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. ...
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...
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...
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....
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(); ...
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...
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...
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...
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...
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 =...
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. ...
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'; } ...
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...