question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
I need to split string by line.
I used to do in the following way:
int doSegment(char *sentence, int segNum)
{
assert(pSegmenter != NULL);
Logger &log = Logger::getLogger();
char delims[] = "\n";
char *line = NULL;
if (sentence != NULL)
{
line = strtok(sentence, delims);
while(line != NULL)
{
cout <... | I'd like to use std::getline or std::string::find to go through the string.
below code demonstrates getline function
int doSegment(char *sentence)
{
std::stringstream ss(sentence);
std::string to;
if (sentence != NULL)
{
while(std::getline(ss,to,'\n')){
cout << to <<endl;
}
}
return 0;
}
| Split | 13,172,158 | 46 |
I want to split a string by a list of indices, where the split segments begin with one index and end before the next one.
Example:
s = 'long string that I want to split up'
indices = [0,5,12,17]
parts = [s[index:] for index in indices]
for part in parts:
print part
This will return:
long string that I want to s... | s = 'long string that I want to split up'
indices = [0,5,12,17]
parts = [s[i:j] for i,j in zip(indices, indices[1:]+[None])]
returns
['long ', 'string ', 'that ', 'I want to split up']
which you can print using:
print '\n'.join(parts)
Another possibility (without copying indices) would be:
s = 'long string that I w... | Split | 10,851,445 | 46 |
I'm trying to learn python/django.
Right now, I have all of my models in models.py
Is it possible to have my models broken out so that I can have a single file per model in a separate models folder so that I can do something like:
~/myproject/myapp/models/user.py
~/myproject/myapp/models/group.py
Thanks
| It is possible, just make sure to import all the models you create in __init__.py in your models directory. In your case, it would look like this:
# __init__.py
from .user import UserModel
from .group import GroupModel
This needs to be done because Django looks in app.models for an app's models.
As others have mention... | Split | 5,534,206 | 46 |
In python:
s = '1::3'
a = s.split(':')
print(a[0]) # '1' good
print(a[1]) # '' good
print(a[2]) # '3' good
How can I achieve the same effect with zsh?
The following attempt fails:
string="1::3"
a=(${(s/:/)string})
echo $a[1] # 1
echo $a[2] # 3 ?? I want an empty string, as in Python
| The solution is to use the @ modifier, as indicated in the zsh docs:
string="1::3"
a=("${(@s/:/)string}") # @ modifier
By the way, if one has the choice of the delimiter, it's much easier and less error prone to use a newline as a delimiter. The right way to split the lines with zsh is then:
a=("${(f)string}")
I don'... | Split | 2,930,238 | 46 |
I have the name of a file like this: name1.csv and I would like to extract two substrings of this string. One that stores the name1 in one variable and other that stores the extension, csv, without the dot in another variable.
I have been searching if there is a function like indexOf of Java that allows to do that kind... | Use strsplit:
R> strsplit("name1.csv", "\\.")[[1]]
[1] "name1" "csv"
R>
Note that you a) need to escape the dot (as it is a metacharacter for regular expressions) and b) deal with the fact that strsplit() returns a list of which typically only the first element is of interest.
A more general solution involves regul... | Split | 14,173,754 | 45 |
I have following data:
1||1||Abdul-Jabbar||Karim||1996||1974
I want to delimit the tokens.
Here the delimiter is "||".
My delimiter setter is:
public void setDelimiter(String delimiter) {
char[] c = delimiter.toCharArray();
this.delimiter = "\"" + "\\" + c[0] + "\\" + c[1] + "\"";
System.out.println("Delim... | There is no need to set the delimiter by breaking it up in pieces like you have done.
Here is a complete program you can compile and run:
import java.util.Arrays;
public class SplitExample {
public static final String PLAYER = "1||1||Abdul-Jabbar||Karim||1996||1974";
public static void main(String[] args) {
... | Split | 7,021,074 | 45 |
I'm trying to split a tab delimitted field in bash.
I am aware of this answer: how to split a string in shell and get the last field
But that does not answer for a tab character.
I want to do get the part of a string before the tab character, so I'm doing this:
x=`head -1 my-file.txt`
echo ${x%\t*}
But the \t is match... | If your file look something like this (with tab as separator):
1st-field 2nd-field
you can use cut to extract the first field (operates on tab by default):
$ cut -f1 input
1st-field
If you're using awk, there is no need to use tail to get the last line, changing the input to:
1:1st-field 2nd-field
2:1st-field ... | Split | 6,654,849 | 45 |
I want to split a string using the backslash ('\'). However, it's not allowed - the compiler says "newline in constant". Is there a way to split using backslash?
//For example...
String[] breakApart = sentence.Split('\'); //this gives an error.
| Try using the escaped character '\\' instead of '\':
String[] breakApart = sentence.Split('\\');
The backslash \ in C# is used as an escape character for special characters like quotes and apostrophes. So when you are trying to wrap the backslash with apostrophes, the backslash together with the final apostrophe is b... | Split | 16,783,616 | 44 |
Possible Duplicate:
How to split a String by space
I need help while parsing a text file.
The text file contains data like
This is different type of file.
Can not split it using ' '(white space)
My problem is spaces between words are not similar. Sometimes there is single space and sometimes multiple spa... | str.split("\\s+") would work. The + at the end of the regular-expression, would treat multiple spaces the same as a single space. It returns an array of strings (String[]) without any " " results.
| Split | 13,081,527 | 44 |
How can I reverse the results of a shlex.split? That is, how can I obtain a quoted string that would "resemble that of a Unix shell", given a list of strings I wish quoted?
Update0
I've located a Python bug, and made corresponding feature requests here.
| We now (3.3) have a shlex.quote function. It’s none other that pipes.quote moved and documented (code using pipes.quote will still work). See http://bugs.python.org/issue9723 for the whole discussion.
subprocess.list2cmdline is a private function that should not be used. It could however be moved to shlex and made o... | Split | 4,748,344 | 44 |
I've googled and I'm just not getting it. Seems like such a simple function, but of course Lua doesn't have it.
In Python I would do
string = "cat,dog"
one, two = string.split(",")
and then I would have two variables, one = cat. two = dog
How do I do this in Lua!?
| Try this
str = 'cat,dog'
for word in string.gmatch(str, '([^,]+)') do
print(word)
end
'[^,]' means "everything but the comma, the + sign means "one or more characters". The parenthesis create a capture (not really needed in this case).
| Split | 19,262,761 | 43 |
I am trying to parse some data using Java which is separated by '|' sequence. Below is an example of the data.
String s = "111206|00:00:00|2|64104|58041";
String [] temp = s.split("|");
for(String p: temp)
System.out.println(p);
But instead of splitting at '|' it separates every character separately. Here is the outpu... | You must use:
String [] temp = s.split("\\|");
This is because the split method takes a regular expression, and | is one of the special characters. It means 'or'. That means you are splitting by '' or '', which is just ''. Therefore it will split between every character.
You need two slashes because the first one is f... | Split | 16,311,651 | 43 |
I need to make sure none of the lines in my code exceeds a a certain length.
Normally I separate lines where there's a comma or another suitable break.
How can I separate this line into 2?
cout<<"Error:This is a really long error message that exceeds the maximum permitted length.\n";
If I just press enter somewhere in... | Two options:
cout << "Error:This is a really long "
<< "error message that exceeds "
<< "the maximum permitted length.\n";
Or:
cout << "Error:This is a really long "
"error message that exceeds "
"the maximum permitted length.\n";
The second one is more efficient.
| Split | 969,394 | 43 |
I want to split a directory from a large Subversion repository to a repository of its own, and keep the history of the files in that directory.
I tried the regular way of doing it first
svnadmin dump /path/to/repo > largerepo.dump
cat largerepo.dump | svndumpfilter include my/directory >mydir.dump
but that does not wo... | I had a similar problem splitting a repository ..
svndumpfilter: Invalid copy source path /dir/old_dir
What I did to get around the problem was to include the additional old directories that is was requesting, or that you know you moved. In my case I had moved 3 directories into another directory.
eg. Moved Folders A... | Split | 433,276 | 43 |
I have a string in a node and I'd like to split the string on '?' and return the last item in the array.
For example, in the block below:
<a>
<xsl:attribute name="href">
/newpage.aspx?<xsl:value-of select="someNode"/>
</xsl:attribute>
Link text
</a>
I'd like to split the someNode value.
Edit:
Here... | Use a recursive method:
<xsl:template name="output-tokens">
<xsl:param name="list" />
<xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" />
<xsl:variable name="first" select="substring-before($newlist, ' ')" />
<xsl:variable name="remaining" select="substring-after($newlist, ' ... | Split | 136,500 | 43 |
I have a string
s = 'abcd qwrre qwedsasd zxcwsacds'
I want to split any string in only two parts at the first occurrence of a whitespace. i.e. a='abcd' and b='qwrre qwedsasd zxcwsacds'
If I use a, b=split(' ') it gives me an error because there are too many values to unpack.
| You could use a,b = split(' ', 1).
The second argument 1 is the maximum number of splits that would be done.
s = 'abcd efgh hijk'
a,b = s.split(' ', 1)
print(a) #abcd
print(b) #efgh hijk
For more information on the string split function, see str.split in the manual.
| Split | 50,848,764 | 42 |
How to split a string into an tokens and then save them in an array?
Specifically, I have a string "abc/qwe/jkh". I want to separate "/", and then save the tokens into an array.
Output will be such that
array[0] = "abc"
array[1] = "qwe"
array[2] = "jkh"
please help me
| #include <stdio.h>
#include <string.h>
int main ()
{
char buf[] ="abc/qwe/ccd";
int i = 0;
char *p = strtok (buf, "/");
char *array[3];
while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, "/");
}
for (i = 0; i < 3; ++i)
printf("%s\n", array[i]);
return ... | Split | 15,472,299 | 42 |
How exactly can you take a string, split it, reverse it and join it back together again without the brackets, commas, etc. using python?
| >>> tmp = "a,b,cde"
>>> tmp2 = tmp.split(',')
>>> tmp2.reverse()
>>> "".join(tmp2)
'cdeba'
or simpler:
>>> tmp = "a,b,cde"
>>> ''.join(tmp.split(',')[::-1])
'cdeba'
The important parts here are the split function and the join function. To reverse the list you can use reverse(), which reverses the list in place or the... | Split | 3,627,270 | 42 |
I'm currently trying to split a string in C# (latest .NET and Visual Studio 2008), in order to retrieve everything that's inside square brackets and discard the remaining text.
E.g.: "H1-receptor antagonist [HSA:3269] [PATH:hsa04080(3269)]"
In this case, I'm interested in getting "HSA:3269" and "PATH:hsa04080(3269)" in... | Split won't help you here; you need to use regular expressions:
// using System.Text.RegularExpressions;
// pattern = any number of arbitrary characters between square brackets.
var pattern = @"\[(.*?)\]";
var query = "H1-receptor antagonist [HSA:3269] [PATH:hsa04080(3269)]";
var matches = Regex.Matches(query, pattern)... | Split | 740,642 | 42 |
I was trying to split a string based on multiple delimiters by referring How split a string in jquery with multiple strings as separator
Since multiple delimiters I decided to follow
var separators = [' ', '+', '-', '(', ')', '*', '/', ':', '?'];
var tokens = x.split(new RegExp(separators.join('|'), 'g'));... | escape needed for regex related characters +,-,(,),*,?
var x = "adfds+fsdf-sdf";
var separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?'];
console.log(separators.join('|'));
var tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);
http://jsfiddle.net/cpdjZ/
| Split | 19,313,541 | 41 |
I'm trying to perform a string split on a set of somewhat irregular data that looks something like:
\n\tName: John Smith
\n\t Home: Anytown USA
\n\t Phone: 555-555-555
\n\t Other Home: Somewhere Else
\n\t Notes: Other data
\n\tName: Jane Smith
\n\t Misc: Data with spaces
I'd like to convert this into a tuple/dic... | Just use .strip(), it removes all whitespace for you, including tabs and newlines, while splitting. The splitting itself can then be done with data_string.splitlines():
[s.strip() for s in data_string.splitlines()]
Output:
>>> [s.strip() for s in data_string.splitlines()]
['Name: John Smith', 'Home: Anytown USA', 'Pho... | Split | 12,533,955 | 41 |
I want to extract the substrings from a string in MySQL. The string contains multiple substrings separated by commas(','). I need to extract these substrings using any MySQL functions.
For example:
Table Name: Product
-----------------------------------
item_code name colors
-----------------------------------
10... | A possible duplicate of this: Split value from one field to two
Unfortunately, MySQL does not feature a split string function.
As in the link above indicates there are User-defined Split function.
A more verbose version to fetch the data can be the following:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(colors, ',', 1), ',',... | Split | 34,992,575 | 40 |
Given the ruby code:
"aaaa\nbbbb\n\n".split(/\n/)
This outputs:
["aaaa", "bbbb"]
I would like the output to include the blank line indicated by \n\n -- I want the result to be:
["aaaa", "bbbb", ""]
What is the easiest/best way to get this exact result?
| I'd recommend using lines instead of split for this task. lines will retain the trailing line-break, which allows you to see the desired empty-line. Use chomp to clean up:
"aaaa\nbbbb\n\n".lines.map(&:chomp)
[
[0] "aaaa",
[1] "bbbb",
[2] ""
]
Other, more convoluted, ways of getting there are:
"aaaa\nbbbb\... | Split | 12,062,126 | 40 |
I have a string such as:
"aabbccccdd"
I want to break this string into a vector of substrings of length 2 :
"aa" "bb" "cc" "cc" "dd"
| Here is one way
substring("aabbccccdd", seq(1, 9, 2), seq(2, 10, 2))
#[1] "aa" "bb" "cc" "cc" "dd"
or more generally
text <- "aabbccccdd"
substring(text, seq(1, nchar(text)-1, 2), seq(2, nchar(text), 2))
#[1] "aa" "bb" "cc" "cc" "dd"
Edit: This is much, much faster
sst <- strsplit(text, "")[[1]]
out <- paste0(sst[c(T... | Split | 11,619,616 | 40 |
I tried to search online to solve this question but I didn't found anything.
I wrote the following abstract code to explain what I'm asking:
String text = "how are you?";
String[] textArray= text.splitByNumber(4); //this method is what I'm asking
textArray[0]; //it contains "how "
textArray[1]; //it contains "are "
te... | I think that what he wants is to have a string split into substrings of size 4. Then I would do this in a loop:
List<String> strings = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
strings.add(text.substring(index, Math.min(index + 4,text.length())));
index += 4;
}
| Split | 9,276,639 | 40 |
I have a dataframe made up of 400'000 rows and about 50 columns. As this dataframe is so large, it is too computationally taxing to work with.
I would like to split this dataframe up into smaller ones, after which I will run the functions I would like to run, and then reassemble the dataframe at the end.
There is no ... | Make your own grouping variable.
d <- split(my_data_frame,rep(1:400,each=1000))
You should also consider the ddply function from the plyr package, or the group_by() function from dplyr.
edited for brevity, after Hadley's comments.
If you don't know how many rows are in the data frame, or if the data frame might be an ... | Split | 7,060,272 | 40 |
Is there a way to tell the split command to save the resultant files in a particular location?
| How about:
$ split -b 10 input.txt xxx/split-file
or
$ split -b 10 input.txt /tmp/split-file
Just include the output directory in the prefix specification. Keep in mind that the directory must be created beforehand.
| Split | 4,701,114 | 40 |
I am splitting file names in Go to get at the file extension (e.g. import ("strings") ; strings.Split("example.txt", ".")).
For this reason, I would like to return the last item in the slice returned by the split, i.e.
for strings.Split("ex.txt", "."), I want txt
This question suggests that doing
strings.Split("ex.tx... | strings.LastIndex makes this quite neat:
s := "Hello,Stack,Overflow"
last := s[strings.LastIndex(s, ",")+1:]
fmt.Println(last)
returns "Overflow". If the search string isn't found it returns the whole string, which is logical.
Playground here
| Split | 50,311,213 | 39 |
The following code returns into a nice readable output.
def add_line_remove_special(ta_from,endstatus,*args,**kwargs):
try:
ta_to = ta_from.copyta(status=endstatus)
infile = botslib.opendata(ta_from.filename,'r')
tofile = botslib.opendata(str(ta_to.idta),'wb')
start = infile.readline... | To get all text on a line after a underscore character, split on the first _ character and take the last element of the result:
line.split('_', 1)[-1]
This will also work for lines that do not have an underscore character on the line.
Demo:
>>> 'Grp25_QTY47 5'.split('_', 1)[-1]
'QTY47 5'
>>... | Split | 16,405,601 | 39 |
I'd like to split a string using the Split function in the Regex class. The problem is that it removes the delimiters and I'd like to keep them. Preferably as separate elements in the splitee.
According to other discussions that I've found, there are only inconvenient ways to achieve that.
Any suggestions?
| Just put the pattern into a capture-group, and the matches will also be included in the result.
string[] result = Regex.Split("123.456.789", @"(\.)");
Result:
{ "123", ".", "456", ".", "789" }
This also works for many other languages:
JavaScript: "123.456.789".split(/(\.)/g)
Python: re.split(r"(\.)", "123.456.789")
... | Split | 15,667,927 | 39 |
var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix
I would like the array to be like this:
var astr = ["single", "words", "fixed string of words"];
| The accepted answer is not entirely correct. It separates on non-space characters like . and - and leaves the quotes in the results. The better way to do this so that it excludes the quotes is with capturing groups, like such:
//The parenthesis in the regex creates a captured group within the quotes
var myRegexp = ... | Split | 2,817,646 | 39 |
"something here ; and there, oh,that's all!"
I want to split it by ; and ,
so after processing should get:
something here
and there
oh
that's all!
| <?php
$pattern = '/[;,]/';
$string = "something here ; and there, oh,that's all!";
echo '<pre>', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';
| Split | 1,452,777 | 39 |
If I have a Vim window open with 2 splits in it (3 total buffers visible) and I've adjusted the viewport of each split, then I close one buffer, the other two buffer's viewport's are automatically resized.
Is there a way to maintain or at least better scale the split when I close a buffer?
1) Vim window with three spli... | set noea
In other words:
set noequalalways
See equalalways in the Vim documentation.
| Split | 486,027 | 39 |
I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this:
byte[] largeBytes = [1,2,3,4,5,6,... | In C# with Linq you can do this:
smallPortion = largeBytes.Take(4).ToArray();
largeBytes = largeBytes.Skip(4).Take(5).ToArray();
;)
| Split | 20,797 | 39 |
I have a list of bytes and I want to split this list into smaller parts.
var array = new List<byte> {10, 20, 30, 40, 50, 60};
This list has 6 cells. For example, I want to split it into 3 parts containing each 2 bytes.
I have tried to write some for loops and used 2D arrays to achieve my purpose but I don't know it is... | A nice way would be to create a generic/extension method to split any array. This is mine:
/// <summary>
/// Splits an array into several smaller arrays.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array to split.</param>
/// <param name="size">The size of the s... | Split | 18,986,129 | 38 |
I have a data file with columns like
BBP1 0.000000 -0.150000 2.033000 0.00 -0.150 1.77
and the individual columns are separated by a varying number of whitespaces.
My goal is to read in those lines, do some math on several rows, for example multiplying column 4 by .95, and write them out to a new file. The ne... | You want to use re.split() in that case, with a group:
re.split(r'(\s+)', line)
would return both the columns and the whitespace so you can rejoin the line later with the same amount of whitespace included.
Example:
>>> re.split(r'(\s+)', line)
['BBP1', ' ', '0.000000', ' ', '-0.150000', ' ', '2.033000', ' ', '... | Split | 15,579,271 | 38 |
Following is my REPL output. I am not sure why string.split does not work here.
val s = "Pedro|groceries|apple|1.42"
s: java.lang.String = Pedro|groceries|apple|1.42
scala> s.split("|")
res27: Array[java.lang.String] = Array("", P, e, d, r, o, |, g, r, o, c, e, r, i, e, s, |, a, p, p, l, e, |, 1, ., 4, 2)
| If you use quotes, you're asking for a regular expression split. | is the "or" character, so your regex matches nothing or nothing. So everything is split.
If you use split('|') or split("""\|""") you should get what you want.
| Split | 11,284,771 | 38 |
I have a string that's like this: 1|"value"|;
I want to split that string and have chosen | as the separator.
My code looks like this:
String[] separated = line.split("|");
What I get is an array that contains all characters as one entry:
separated[0] = ""
separated[1] = "1"
separated[2] = "|"
separated[3] = """
separ... | | is treated as an OR in RegEx. So you need to escape it:
String[] separated = line.split("\\|");
| Split | 6,305,675 | 38 |
I'm trying to find a good way to split a string using a regular expression instead of a string. Thanks
http://nsf.github.io/go/strings.html?f:Split!
| You can use regexp.Split to split a string into a slice of strings with the regex pattern as the delimiter.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("[0-9]+")
txt := "Have9834a908123great10891819081day!"
split := re.Split(txt, -1)
set := []string{}
f... | Split | 4,466,091 | 38 |
I am trying to find a Unix command (combination, maybe) on how to continuously display a file of its last several lines of contents. But during this displaying, I want some of the top lines are always displayed on the screen top when the rolling contents reach the screen top.
Is that possible?
Suppose I have file, "jo... | I use this function all the time to monitor a log file in another terminal window.
tail -f <filename>
I recommend taking it a step forward to look for particular text in the log. Great if you are only interested in seeing some particular entry being written to the file.
tail -f <filename> | grep <keyword or pattern>
| Split | 14,604,397 | 37 |
I have string: @address = "10 Madison Avenue, New York, NY - (212) 538-1884"
What's the best way to split it like this?
<p>10 Madison Avenue,</p>
<p>New York, NY - (212) 538-1884</p>
| String#split has a second argument, the maximum number of fields returned in the result array:
http://ruby-doc.org/core/classes/String.html#M001165
@address.split(",", 2) will return an array with two strings, split at the first occurrence of ",".
the rest of it is simply building the string using interpolation or if y... | Split | 6,594,649 | 37 |
How do I take a string in Perl and split it up into an array with entries two characters long each?
I attempted this:
@array = split(/../, $string);
but did not get the expected results.
Ultimately I want to turn something like this
F53CBBA476
in to an array containing
F5 3C BB A4 76
| @array = ( $string =~ m/../g );
The pattern-matching operator behaves in a special way in a list context in Perl. It processes the operation iteratively, matching the pattern against the remainder of the text after the previous match. Then the list is formed from all the text that matched during each application of ... | Split | 372,370 | 37 |
Using JavaScript to split a date and rearrange the format.
Date is provided through a json feed as YYYY-MM-DD.
To get the date, I do:
var og_date = (v.report[totalItems -1].inspection_date);
console.log(og_date);
console log correctly shows the date, ie "2012-10-01".
Next, I try to split the date, for example:
consol... | Your question answers itself ;) If og_date contains the date, it's probably a string, so og_date.value is undefined.
Simply use og_date.split('-') instead of og_date.value.split('-')
| Split | 24,210,445 | 36 |
Is there a way to split a string by some symbol but only at first occurrence?
Example: date: '2019:04:01' should be split into date and '2019:04:01'
It could also look like this date:'2019:04:01' or this date : '2019:04:01' and should still be split into date and '2019:04:01'
string.split(':');
I tried using th... | You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:
String s = "date : '2019:04:01'";
int idx = s.indexOf(":");
List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];
| Split | 60,402,195 | 36 |
What I am trying to accomplish is splitting a column into multiple columns. I would prefer the first column to contain "F", second column "US", third "CA6" or "DL", and the fourth to be "Z13" or "U13" etc etc. My entire df follows the same pattern of X.XX.XXXX.XXX or X.XX.XXX.XXX or X.XX.XX.XXX and I know the third c... | A very direct way is to just use read.table on your character vector:
> read.table(text = text, sep = ".", colClasses = "character")
V1 V2 V3 V4
1 F US CLE V13
2 F US CA6 U13
3 F US CA6 U13
4 F US CA6 U13
5 F US CA6 U13
6 F US CA6 U13
7 F US CA6 U13
8 F US CA6 U13
9 F US DL U13
10 F US DL U13
... | Split | 18,641,951 | 36 |
I am wondering what this line of code does to a url that is contained in a String called surl?
String[] stokens = surl.split("\\s*,\\s*");
Lets pretend this is the surl = "http://myipaddress:8080/Map/MapServer.html"
What will stokens be?
| That regex "\\s*,\\s*" means:
\s* any number of whitespace characters
a comma
\s* any number of whitespace characters
which will split on commas and consume any spaces either side
| Split | 13,750,716 | 36 |
String incomingNumbers[ ] = writtenNumber.split("\\-");
The program accepts natural language numbers such as thirty-two or five.
So if five is entered, what lands in my incomingNumbers array?
| You get an array of size 1 holding the original value:
Input Output
----- ------
thirty-two {"thirty", "two"}
five {"five"}
You can see this in action in the following program:
class Test {
static void checkResult (String input) {
String [] arr = input.split ("\\-");
System.out.... | Split | 11,770,502 | 36 |
What I'm trying to do:
I am trying to split a vector into two separate arrays. The current int vector contains an element per line in a text file. The text file is a list of random integers.
How I'm planning to do it:
My current idea is to create two regular int arrays, then iterate over the entire vector and copy ... | Use iterators.
std::vector<int> lines;
// fill
std::size_t const half_size = lines.size() / 2;
std::vector<int> split_lo(lines.begin(), lines.begin() + half_size);
std::vector<int> split_hi(lines.begin() + half_size, lines.end());
Since iterator ranges represent half open ranges [begin, end), you don't need to add 1 t... | Split | 9,811,235 | 36 |
I need a MySQL function to get the left part of a string with variable length, before the separator.
For example, with separator string '==' :
abcdef==12345 should return abcdef
abcdefgh==12 should return abcdefgh
Also the same thing, but for the right part...
| SELECT SUBSTRING_INDEX(column_name, '==', 1) FROM table ; // for left
SELECT SUBSTRING_INDEX(column_name, '==', -1) FROM table; // for right
| Split | 5,734,504 | 36 |
I have a nice CamelCase string such as ImageWideNice or ImageNarrowUgly. Now I want to break that string in its substrings, such as Image, Wide or Narrow, and Nice or Ugly.
I thought this could be solved simply by
camelCaseString =~ /(Image)((Wide)|(Narrow))((Nice)|(Ugly))/
But strangely, this will only fill $1 and $2... | s = 'nowIsTheTime'
s.split /(?=[A-Z])/
=> ["now", "Is", "The", "Time"]
?=pattern is an example of positive lookahead. It essentially matches a point in the string right before pattern. It doesn't consume the characters, that is, it doesn't include pattern as part of the match. Another example:
irb> 'streets'.s... | Split | 3,997,516 | 36 |
I want to explode a string for all:
whitespaces (\n \t etc)
comma
hyphen (small dash). Like this >> -
But this does not work:
$keywords = explode("\n\t\r\a,-", "my string");
How to do that?
| Explode can't do that. There is a nice function called preg_split for that. Do it like this:
$keywords = preg_split("/[\s,-]+/", "This-sign, is why we can't have nice things");
var_dump($keywords);
This outputs:
array
0 => string 'This' (length=4)
1 => string 'sign' (length=4)
2 => string 'is' (length=2)
3 ... | Split | 3,679,033 | 36 |
I have a large number of PDF files which have two slides to a page (for printing).
The format is A4 pages each with two slides setup like so:
-----------
| slide 1 |
-----------
| slide 2 |
-----------
How can I generate a new PDF file with one slide per page?
Happy to use GUI, CLI, scripts or even interface with a la... | PDF Scissors allowed me to bulk split (crop) all pages in a PDF.
| Split | 13,345,593 | 35 |
Suppose I have a long string:
"XOVEWVJIEWNIGOIWENVOIWEWVWEW"
How do I split this to get every 5 characters followed by a space?
"XOVEW VJIEW NIGOI WENVO IWEWV WEW"
Note that the last one is shorter.
I can do a loop where I constantly count and build a new string character by character but surely there must be someth... | Using regular expressions:
gsub("(.{5})", "\\1 ", "XOVEWVJIEWNIGOIWENVOIWEWVWEW")
# [1] "XOVEW VJIEW NIGOI WENVO IWEWV WEW"
| Split | 26,497,583 | 35 |
I want to split std::string by regex.
I have found some solutions on Stackoverflow, but most of them are splitting string by single space or using external libraries like boost.
I can't use boost.
I want to split string by regex - "\\s+".
I am using this g++ version g++ (Debian 4.4.5-8) 4.4.5 and i can't upgrade.
| #include <regex>
std::regex rgx("\\s+");
std::sregex_token_iterator iter(string_to_split.begin(),
string_to_split.end(),
rgx,
-1);
std::sregex_token_iterator end;
for ( ; iter != end; ++iter)
std::cout << *iter << '\n';
The -1 is the key here: when the iterator is constructed the iterator points at th... | Split | 16,749,069 | 35 |
How can I insert a string before the extension in an image filename? For example, I need to convert this:
../Course/Assess/Responsive_Course_1_1.png
to this:
../Course/Assess/Responsive_Course_1_1_large.png
| If we assume that an extension is any series of letters, numbers, underscore or dash after the last dot in the file name, then:
filename = filename.replace(/(\.[\w\d_-]+)$/i, '_large$1');
| Split | 10,802,273 | 35 |
I’m trying to split a String. Simple examples work:
groovy:000> print "abc,def".split(",");
[abc, def]===> null
groovy:000>
But instead of a comma, I need to split it on pipes, and I’m not getting the desired result:
groovy:000> print "abc|def".split("|");
[, a, b, c, |, d, e, f]===> null
groovy:000>
So of course my ... | You need to split on \\|.
| Split | 3,842,537 | 35 |
I have the following data frame and I want to break it up into 10 different data frames. I want to break the initial 100 row data frame into 10 data frames of 10 rows. I could do the following and get the desired results.
df = data.frame(one=c(rnorm(100)), two=c(rnorm(100)), three=c(rnorm(100)))
df1 = df[1:10,]
df2 = ... | > str(split(df, (as.numeric(rownames(df))-1) %/% 200))
List of 6
$ 0:'data.frame': 200 obs. of 3 variables:
..$ one : num [1:200] -1.592 1.664 -1.231 0.269 0.912 ...
..$ two : num [1:200] 0.639 -0.525 0.642 1.347 1.142 ...
..$ three: num [1:200] -0.45 -0.877 0.588 1.188 -1.977 ...
$ 1:'data.frame': 200 ob... | Split | 14,164,525 | 34 |
Possible Duplicate:
Python program to split a list into two lists with alternating elements
Problem
Given a list like this:
list1 = [blah, 3, haha, 2, pointer, 1, abcd, fire]
I expect to get this output:
list = [3, 2, 1, fire]
So what I want is to make a list of even elements of the former list.
What I tried
I trie... | You can use list slicing. The following snippet will do.
list1 = ['blah', 3, 'haha', 2, 'pointer', 1, 'poop', 'fire']
listOdd = list1[1::2] # Elements from list1 starting from 1 iterating by 2
listEven = list1[::2] # Elements from list1 starting from 0 iterating by 2
print listOdd
print listEven
Output
[3, 2, 1, 'fire... | Split | 11,702,414 | 34 |
example String :
/gasg/string
expected result : string
Characters to to remove: all characters between the "/" symbols including the symbols
| Also awk - use slash as separator and print last field
echo "/gas/string" | awk -F/ '{print $NF}'
Or cut - but that will only work if you have same number of directories to strip
echo "/gasg/string" |cut -d/ -f 3
| Split | 10,776,679 | 34 |
I've come across this several times in the past and have finally decided to find out why.
StringSplitOptions.RemoveEmptyEntries would suggest that it removes empty entries.
So why does this test fail?
var tags = "One, Two, , Three, Foo Bar, , Day , ";
var tagsSplit = tags.Split(new[] { ',' }, StringSplitOptions.R... | Most likely because you change the string after the split. You trim the values after splitting them, RemoveEmptyEntries doesn't consider the string " " empty.
The following would achieve what you want, basically creating your own strip empty elements:
var tagsSplit = tags.Split(',').
Select(tag => tag... | Split | 10,682,301 | 34 |
I have recently figured out that I haven't been using regex properly in my code. Given the example of a tab delimited string str, I have been using str.split("\t"). Now I realize that this is wrong and to match the tabs properly I should use str.split("\\t").
However I happen to stumble upon this fact by pure chance, a... | When using "\t", the escape sequence \t is replaced by Java with the character U+0009. When using "\\t", the escape sequence \\ in \\t is replaced by Java with \, resulting in \t that is then interpreted by the regular expression parser as the character U+0009.
So both notations will be interpreted correctly. It’s just... | Split | 3,762,347 | 34 |
I have this text file that I read into a Java application and then count the words in it line by line. Right now I am splitting the lines into words by a
String.split([\\p{Punct}\\s+])"
But I know I am missing out on some words from the text file. For example, the word "can't" should be divided into two words "can" a... | You have one small mistake in your regex. Try this:
String[] Res = Text.split("[\\p{Punct}\\s]+");
[\\p{Punct}\\s]+ move the + form inside the character class to the outside. Other wise you are splitting also on a + and do not combine split characters in a row.
So I get for this code
String Text = "But I know. For exa... | Split | 7,384,791 | 33 |
I have a csv file which looks like this
$lines[0] = "text, with commas", "another text", 123, "text",5;
$lines[1] = "some without commas", "another text", 123, "text";
$lines[2] = "some text with commas or no",, 123, "text";
And I would like to have a table:
$t[0] = array("text, with commas", "another text", "123", "t... | You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.
Example from PHP Manual:
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /><... | Split | 2,805,427 | 33 |
I have a comma separated string in R:-
"a,b,c"
I want to convert it into a list which looks like this:
list("a","b","c")
How do I do that?
| This is a basic strsplit problem:
x <- "a,b,c"
as.list(strsplit(x, ",")[[1]])
# [[1]]
# [1] "a"
#
# [[2]]
# [1] "b"
#
# [[3]]
# [1] "c"
strsplit creates a list and the [[1]] selects the first list item (we only have one, in this case). The result at this point is just a regular character vector, but you want it in a... | Split | 24,256,044 | 33 |
I wonder if it's possible to use split to devide a string with several parts that are separated with a comma, like this:
title, genre, director, actor
I just want the first part, the title of each string and not the rest?
| string valueStr = "title, genre, director, actor";
var vals = valueStr.Split(',')[0];
vals will give you the title
| Split | 10,868,517 | 33 |
My current Python project will require a lot of string splitting to process incoming packages. Since I will be running it on a pretty slow system, I was wondering what the most efficient way to go about this would be. The strings would be formatted something like this:
Item 1 | Item 2 | Item 3 <> Item 4 <> Item 5
Expl... | I was slightly surprised that split() performed so badly in your code, so I looked at it a bit more closely and noticed that you're calling list.remove() in the inner loop. Also you're calling split() an extra time on each string. Get rid of those and a solution using split() beats the regex hands down on shorter strin... | Split | 9,602,856 | 33 |
I am working on an application which imports thousands of lines where every line has a format like this:
|* 9070183020 |04.02.2011 |107222 |M/S SUNNY MEDICOS |GHAZIABAD | 32,768.00 |
I am using the following Regex to split the lines to the data I need:
Regex lineS... | Regex lineSplitter = new Regex(@"[\s*\*]*\|[\s*\*]*");
var columns = lineSplitter.Split(data).Where(s => s != String.Empty);
or you could simply do:
string[] columns = data.Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
foreach (string c in columns) this.textBox1.Text += "[" + c.Trim(' ', '*') + "] " ... | Split | 4,912,365 | 33 |
Does python have a build-in (meaning in the standard libraries) to do a split on strings that produces an iterator rather than a list? I have in mind working on very long strings and not needing to consume most of the string.
| Not directly splitting strings as such, but the re module has re.finditer() (and corresponding finditer() method on any compiled regular expression).
@Zero asked for an example:
>>> import re
>>> s = "The quick brown\nfox"
>>> for m in re.finditer('\S+', s):
... print(m.span(), m.group(0))
...
(0, 3) The
(4, 9)... | Split | 4,586,026 | 33 |
I was trying to split an arithmetic expression (eg "1+2+10+15") on the plus signs. However, I didn't manage to write the appropriate regular expression. I thought this would work:
expression.split("\\+");
but it doesn't. Do you know the correct solution?
| It does. However split(...) returns an array, it does not "transform" your String into a String[]. Try this:
String expression = "1+2+10+1";
String[] tokens = expression.split("\\+");
| Split | 2,198,373 | 33 |
I recently harnessed the power of a look-ahead regular expression to split a String:
"abc8".split("(?=\\d)|\\W")
If printed to the console this expression returns:
[abc, 8]
Very pleased with this result, I wanted to transfer this to Guava for further development, which looked like this:
Splitter.onPattern("(?=\\d)|\\... | You found a bug!
System.out.println(s.split("abc82")); // [abc, 8]
System.out.println(s.split("abc8")); // [abc]
This is the method that Splitter uses to actually split Strings (Splitter.SplittingIterator::computeNext):
@Override
protected String computeNext() {
/*
* The returned string will be from the end of ... | Split | 30,941,743 | 32 |
I have a 'date-time column 'Start' in the format "Y-m-d H:M:S". I want to split this column into a "Date" and a "time" column.
I have tried the following:
df$Date <- sapply(strsplit(as.character(df$Start), " "), "[", 1)
df$Time <- sapply(strsplit(as.character(df$Start), " "), "[", 2)
This works, however, if I use the ... | How about
df$Date <- as.Date(df$Start)
df$Time <- format(df$Start,"%H:%M:%S")
| Split | 19,292,438 | 32 |
I have a string:
a = "1;2;3;"
And I would like to split it this way:
foreach (string b in a.split(';'))
How can I make sure that I return only 1, 2, 3 and not an 'empty string'?
If I split 1;2;3 then I will get what I want. But if I split 1;2;3; then I get an extra 'empty string'. I have taken suggestions and done th... | String.Split takes an array when including any StringSplitOptions:
string[] batchstring = batch_idTextBox.Text.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
If you don't need options, the syntax becomes easier:
string[] batchstring = batch_idTextBox.Text.Split(';');
| Split | 7,393,119 | 32 |
I have a csv file of about 5000 rows in python i want to split it into five files.
I wrote a code for it but it is not working
import codecs
import csv
NO_OF_LINES_PER_FILE = 1000
def again(count_file_header,count):
f3 = open('write_'+count_file_header+'.csv', 'at')
with open('import_1458922827.csv', 'rb') as c... | In Python
Use readlines() and writelines() to do that, here is an example:
>>> csvfile = open('import_1458922827.csv', 'r').readlines()
>>> filename = 1
>>> for i in range(len(csvfile)):
... if i % 1000 == 0:
... open(str(filename) + '.csv', 'w+').writelines(csvfile[i:i+1000])
... filename += 1
the... | Split | 36,445,193 | 31 |
I have this parameter
@ID varchar = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20'
I want to do something to split the comma-separated values.
The string_split function doesn't work and I get this error:
The STRING_SPLIT function is available only under compatibility level 130
and I try to alter my database a... | Other approach is to use XML Method with CROSS APPLY to split your Comma Separated Data :
SELECT Split.a.value('.', 'NVARCHAR(MAX)') DATA
FROM
(
SELECT CAST('<X>'+REPLACE(@ID, ',', '</X><X>')+'</X>' AS XML) AS String
) AS A
CROSS APPLY String.nodes('/X') AS Split(a);
Result :
DATA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
... | Split | 46,902,892 | 31 |
I've more than 200 MP3 files and I need to split each one of them by using silence detection. I tried Audacity and WavePad but they do not have batch processes and it's very slow to make them one by one.
The scenario is as follows:
split track whereas silence 2 seconds or more
then add 0.5 s at the start and the end o... | I found pydub to be easiest tool to do this kind of audio manipulation in simple ways and with compact code.
You can install pydub with
pip install pydub
You may need to install ffmpeg/avlib if needed. See this link for more details.
Here is a snippet that does what you asked. Some of the parameters such as silence_th... | Split | 45,526,996 | 31 |
I have following content in a configuration file (sample.cfg),
Time_Zone_Variance(Mins):300
Alert_Interval(Mins):2
Server:10.0.0.9
Port:1840
I'm trying to store an each values after the : by using split in PowerShell. but i'm not able to produce require output.
Can someone tell me how to use PowerShell split for the ... | You can read the contents of the file using Get-Content, then pipe each line through ForEach-Object, then use the split command on each line, taking the second item in the array as follows:
$filename = "sample.cfg"
Get-Content $filename | ForEach-Object {
$_.split(":")[1]
}
Output
300
2
10.0.0.9
1840
Update
I pr... | Split | 24,634,022 | 31 |
I have a list containing various string values. I want to split the list whenever I see WORD. The result will be a list of lists (which will be the sublists of original list) containing exactly one instance of the WORD I can do this using a loop but is there a more pythonic way to do achieve this ?
Example = ['A', 'WOR... | import itertools
lst = ['A', 'WORD', 'B' , 'C' , 'WORD' , 'D']
w = 'WORD'
spl = [list(y) for x, y in itertools.groupby(lst, lambda z: z == w) if not x]
this creates a splitted list without delimiters, which looks more logical to me:
[['A'], ['B', 'C'], ['D']]
If you insist on delimiters to be included, this should ... | Split | 15,357,830 | 31 |
how can I know the number of tokens in a bash variable (whitespace-separated tokens) - or at least, wether it is one or there are more.
| The $# expansion will tell you the number of elements in a variable / array. If you're working with a bash version greater than 2.05 or so you can:
VAR='some string with words'
VAR=( $VAR )
echo ${#VAR[@]}
This effectively splits the string into an array along whitespace (which is the default delimiter), and then coun... | Split | 638,802 | 31 |
I have the following DataFrame, where Track ID is the row index. How can I split the string in the stats column into 5 columns of numbers?
Track ID stats
14.0 (-0.00924175824176, 0.41, -0.742016492568, 0.0036830094242, 0.00251748449963)
28.0 (0.0411538461538, 0.318230769231, 0.758717081514, 0.00264000622468, 0... | And for the other case, assuming it are strings that look like tuples:
In [74]: df['stats'].str[1:-1].str.split(',', expand=True).astype(float)
Out[74]:
0 1 2 3 4
0 -0.009242 0.410000 -0.742016 0.003683 0.002517
1 0.041154 0.318231 0.758717 0.002640 0.010654
2 -0.014435... | Split | 29,370,211 | 30 |
I am trying to split values in string, for example I have a string:
var example = "X Y\nX1 Y1\nX2 Y2"
and I want to separate it by spaces and \n so I want to get something like that:
var 1 = X
var 2 = Y
var 3 = X1
var 4 = Y1
And is it possible to check that after the value X I have an Y? I mean X and Y are Lat and ... | You can replace newlines with spaces and then split by space (or vice versa).
example.replace( /\n/g, " " ).split( " " )
Demo: http://jsfiddle.net/fzYe7/
If you need to validate the string first, it might be easier to first split by newline, loop through the result and validate each string with a regex that splits the... | Split | 17,271,324 | 30 |
I came across this - in my view - strange behaviour:
"a b c".split(maxsplit=1)
TypeError: split() takes no keyword arguments
Why does str.split() not take keyword arguments, even though it would make sense? I found this behavior both in Python2 and Python3.
| See this bug and its superseder.
str.split() is a native function in CPython, and as such exhibits the behavior described here:
CPython implementation detail: An implementation may provide built-in
functions whose positional parameters do not have names, even if they
are ‘named’ for the purpose of documentation, a... | Split | 11,716,687 | 30 |
String input = "THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player... | Just iterate through the string word by word and break whenever a word passes the limit.
public String addLinebreaks(String input, int maxLineLength) {
StringTokenizer tok = new StringTokenizer(input, " ");
StringBuilder output = new StringBuilder(input.length());
int lineLen = 0;
while (tok.hasMoreToke... | Split | 7,528,045 | 30 |
I tried to write the program in Haskell that will take a string of integer numbers delimitated by comma, convert it to list of integer numbers and increment each number by 1.
For example
"1,2,-5,-23,15" -> [2,3,-4,-22,16]
Below is the resulting program
import Data.List
main :: IO ()
main = do
n <- return 1
putSt... | Doesn't Data.List.Split.splitOn do this?
| Split | 4,503,958 | 30 |
Im looking for an elegant way in Scala to split a given string into substrings of fixed size (the last string in the sequence might be shorter).
So
split("Thequickbrownfoxjumps", 4)
should yield
["Theq","uick","brow","nfox","jump","s"]
Of course I could simply use a loop but there has to be a more elegant (functional... | scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList
grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)
| Split | 3,699,725 | 30 |
I want to split a string into each single character. Eg:
Splitting : "Geeta" to "G", "e", "e" , "t", "a"
How can I do this? I want to split a string which don't have any separator
Please help.
| String.ToCharArray()
From MSDN:
This method copies each character (that is, each Char object) in a string to a character array. The first character copied is at index zero of the returned character array; the last character copied is at index Array.Length – 1.
| Split | 3,033,859 | 30 |
I have written this piece of code that splits a string and stores it in a string array:-
String[] sSentence = sResult.split("[a-z]\\.\\s+");
However, I've added the [a-z] because I wanted to deal with some of the abbreviation problem. But then my result shows up as so:-
Furthermore when Everett tried to instruct them... | Parsing sentences is far from being a trivial task, even for latin languages like English. A naive approach like the one you outline in your question will fail often enough that it will prove useless in practice.
A better approach is to use a BreakIterator configured with the right Locale.
BreakIterator iterator = Brea... | Split | 2,687,012 | 30 |
Is it possible, in HTML to write something like:
<a href="bla bla bla bla\
bla bla bla bla">....</a>
The idea is splitting a string attribute in different lines to improve readability.
| Yes that's possible:
https://stackoverflow.com/a/38874964/3135511
The secret is to use tab's instead of space
As well as to use linebreaks
<a href="
bla
bla bla
bla bla bla
bla bla
bla
">....</a>
Try out the code and hover over the ....
And look for the link - it should read just like
... | Split | 22,831,988 | 29 |
I would like to create one separate plot per group in a data frame and include the group in the title.
With the iris dataset I can in base R and ggplot do this
plots1 <- lapply(split(iris, iris$Species),
function(x)
ggplot(x, aes(x=Petal.Width, y=Petal.Length)) +
geom_point() +
ggtitle(x$Species[1])... | Use .$Species to pull the species data into ggtitle:
iris %>% group_by(Species) %>% do(plots=ggplot(data=.) +
aes(x=Petal.Width, y=Petal.Length) + geom_point() + ggtitle(unique(.$Species)))
| Split | 29,034,863 | 29 |
Inspired by the question if {0} quantifier actually makes sense I started playing with some regexes containing {0} quantifier and wrote this small java program that just splits a test phrase based on various test regex:
private static final String TEST_STR =
"Just a test-phrase!! 1.2.3.. @ {(t·e·s·t)}";
private st... | I did some looking into the source of oracles java 1.7.
"{0}"
I found some code that throws "Dangling meta character" when it finds ?, * or + in the main loop. That is, not immediately after some literal, group, "." or anywhere else where quantifiers are explicitly checked for. For some reason, { is not in that list. ... | Split | 22,182,007 | 29 |
I have a very long string that I want to split into 2 pieces.
I ws hoping somebody could help me split the string into 2 separate strings.
I need the first string to be 400 characters long and then the rest in the second string.
| $first400 = substr($str, 0, 400);
$theRest = substr($str, 400);
You can rename your variables to whatever suits you. Those names are just for explanation. Also if you try this on a string less than 400 characters $theRest will be FALSE
| Split | 6,822,683 | 29 |
We are currently working on a chat + (file sharing +) video conference application using HTML5 websockets. To make our application more accessible we want to implement Adaptive Streaming, using the following sequence:
Raw audio/video data client goes to server
Stream is split into 1 second chunks
Encode stream into va... | I think ffmpeg is the main tool you'll want to look at. It's become most well supported open source media manipulator. There is a python wrapper for it. Though it is also possible to access the command line through the subprocess module.
| Split | 4,242,081 | 29 |
For example, if I had the following string:
"this-is-a-string"
Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?
| Here’s another solution:
span = 2
words = "this-is-a-string".split("-")
print ["-".join(words[i:i+span]) for i in range(0, len(words), span)]
| Split | 1,621,906 | 29 |
Hello friends i have string like
Android_a_b.pdf
i want to split it like Android_a_b and pdf
i try following code like
String s="Android_a_b.pdf";
String[] parts = s.split(".");
String part1 = parts[0];
String part2 = parts[1];
when i run above code it give me error like
11-05 09:42:28.922: E/AndroidRuntime(8... | You need to escape . using \
Eg:
String s="Android_a_b.pdf";
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
Now it will split by .
Split(regex) in Java
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argumen... | Split | 26,749,598 | 28 |
In other languages I've used like Erlang and Python, if I am splitting a string and don't care about one of the fields, I can use an underscore placeholder. I tried this in Perl:
(_,$id) = split('=',$fields[1]);
But I get the following error:
Can't modify constant item in list assignment at ./generate_datasets.pl... | undef serves the same purpose in Perl.
(undef, $something, $otherthing) = split(' ', $str);
| Split | 5,917,094 | 28 |
In the Eclipse Helios Java Package Explorer, I see the Java class icons display a small question mark to the right of the 'J', something like [J?]. This icon is shown on each class within one package in my project, but I cannot find an explanation for this in the documentation.
At some point I expect them to disappea... | It means the class is not yet added to the repository.
If your project was checked-out (most probably a CVS project) and you added a new class file, it will have the ? icon.
For other CVS Label Decorations, check http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.user/reference/ref-cvs-decorations... | Helios | 4,307,086 | 118 |
I deleted my ./bin folder in an Eclipse Indigo (super similar to Helios), and now I am wondering how to rebuild my Java project. I just cannot find a button like we can see in Netbeans.
| For Eclipse you can find the rebuild option under Project > Clean and then select the project you want to clean up... that's all.
This will build your project and create a new bin folder.
| Helios | 6,803,322 | 49 |
Java Decompiler (JD) is generally recommended as a good, well, Java Decompiler. JD-Eclipse is the Eclipse plugin for JD.
I had problems on several different machines to get the plugin running. Whenever I tried to open a .class file, the standard "Source not found" editor would show, displaying lowlevel bytecode disasse... | Here's the stuff I ran into:
1) RTFM and install the "Microsoft Visual C++ 2008 SP1 Redistributable Package" mentioned
at top of the installation docs. I missed this at first because the Helios instructions are at the end.
2) Close all open editor tabs before opening a class file. Otherwise it's easy to get an outdate... | Helios | 4,512,066 | 47 |
I am using Eclipse PDT Helios with Aptana Studio on Windows XP SP3.
Very often, my workflow is interrupted because Eclipse starts a DLTK indexing process that lasts 30 seconds, sometimes up to 2 minutes - which is annoying.
I wonder if there is any way to:
Either turn that off or
Run the DLTK indexing process less fre... | PDT 2.2 (the one in Helios) is using a local database engine, H2, to store information. I wrote a post highlighting how to improve the performance of the new indexer.
There might be another way, but it's requires hacking and I haven't tried it myself since the early builds of PDT 2.2 so YMMV: use a newer version of H2... | Helios | 3,414,592 | 26 |
I have eclipse 3.6, i have installed lot of plugins.
But i want to disable some of the plugins but dont know how :(
( I don't want to uninstall them as i may need them in some time future when i work on other projects)
| In preferences, General, Startup and Shutdown. A lot of plugins will appear there with checkboxes. With luck, the one you're hoping to disable appears there.
If your plugin doesn't appear there, then you either have to uninstall it, hope it provides an option to disable itself, or live with it.
| Helios | 4,164,535 | 17 |
In Eclipse (HELIOS) there is an option to scan all source code and search for task tags such as "TODO", "FIXME" etc. The result is then shown in a fine list.
One can access this list by: Windows->Show View->Tasks.
However, it also scans resources directory and libraries, whose task tags are not of my interest. How c... | It is possible.
Open the Tasks view. Then press icon with the down arrow (top right corner of the window, next to minimise button) and press "Configure Contents..."
Either add new configuration or modify TODOs
In the Scope section select "On working set:" and press button "Select..." to create a new workspace
Create a... | Helios | 6,815,418 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.