Split string at nth occurrence of a given character
>>> n = 2
>>> groups = text.split('_')
>>> '_'.join(groups[:n]), '_'.join(groups[n:])
('20_231', 'myString_234')
Seems like this is the most readable way, the alternative is regex)
Split string on Nth occurrence of char
You can use LastIndexOf()
and some subsequent Substring()
calls:
string input = "29/10/2018 14:50:09402325 671";
int index = input.LastIndexOf(':');
string firstPart = input.Substring(0, index);
string secondPart = input.Substring(index + 1);
Fiddle here
However, another thing to ask yourself is if you even need to make it more complicated than it needs to be. It looks like this data will always be of a the same length until that second :
instance right? Why not just split at a known index (i.e not finding the :
first):
string firstPart = input.Substring(0, 16);
string secondPart = input.Substring(17);
Split string by Nth occurrence of a character
You can do it by splitting on , and joining in chunks:
seq = my_string.split(',')
size = 5
[','.join(seq[pos:pos + size]) for pos in range(0, len(seq), size)]
Output:
['abc,kjj,hg,kj,ls', 'jsh,ku,lo,sasad,hh', 'da']
Split string by Nth occurrence of a character
You can do it by splitting on , and joining in chunks:
seq = my_string.split(',')
size = 5
[','.join(seq[pos:pos + size]) for pos in range(0, len(seq), size)]
Output:
['abc,kjj,hg,kj,ls', 'jsh,ku,lo,sasad,hh', 'da']
How to split a string at every Nth occurrence of a character in Java
Maybe one of the worst way without using function available in java , but good like exercise :
public static void main(String[] args){
String s = "234-236-456-567-678-675-453-564";
int nth =0;
int cont =0;
int i=0;
for(;i<s.length();i++){
if(s.charAt(i)=='-')
nth++;
if(nth == 3 || i==s.length()-1){
if(i==s.length()-1) //with this if you preveent to cut the last number
System.out.println(s.substring(cont,i+1));
else
System.out.println(s.substring(cont,i));
nth=0;
cont =i+1;
}
}
}
How to split string at every nth occurrence of character in Java
Take two int variable. One is to count the no of ','. If ',' occurs then the count will move. And if the count is go to 4 then reset it to 0. The other int value will indicate that from where the string will be cut off. it will start from 0 and after the first string will be detected the the end point (char position in string) will be the first point of the next. Use the this start point and current end point (i+1 because after the occurrence happen the i value will be incremented). Finally add the string in the array list. This is a sample code. Hope this will help you. Sorry for my bad English.
String str = "1,,,,,2,3,,1,,3,,";
int k = 0;
int startPoint = 0;
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
k++;
if (k == 4)
{
String ab = str.substring(startPoint, i+1);
System.out.println(ab);
arrayList.add(ab);
startPoint = i+1;
k = 0;
}
}
}
Cutting a string at nth occurrence of a character
You could do it without arrays, but it would take more code and be less readable.
Generally, you only want to use as much code to get the job done, and this also increases readability. If you find this task is becoming a performance issue (benchmark it), then you can decide to start refactoring for performance.
var str = 'this.those.that', delimiter = '.', start = 1, tokens = str.split(delimiter).slice(start), result = tokens.join(delimiter); // those.that console.log(result)
// To get the substring BEFORE the nth occurencevar tokens2 = str.split(delimiter).slice(0, start), result2 = tokens2.join(delimiter); // this
console.log(result2)
How to split a string on the nth occurrence?
There is nothing built in.
You can use the existing Split
, use Take
and Skip
with string.Join
to rebuild the parts that you originally had.
string[] items = input.Split(new char[] {'\t'},
StringSplitOptions.RemoveEmptyEntries);
string firstPart = string.Join("\t", items.Take(nthOccurrence));
string secondPart = string.Join("\t", items.Skip(nthOccurrence))
string[] everythingSplitAfterNthOccurence = items.Skip(nthOccurrence).ToArray();
An alternative is to iterate over all the characters in the string, find the index of the nth occurrence and substring before and after it (or find the next index after the nth, substring on that etc... etc... etc...).
Related Topics
Using a Global Variable With a Thread
How to Read Pdf Files One by One from a Folder in Python
Setting Matplotlib Colorbar Range
How to Repeat Each Test Multiple Times in a Py.Test Run
Unable to Install Psycopg2 (Pip Install Psycopg2)
How to Change the File Name of an Uploaded File in Django
Animate a Rotating 3D Graph in Matplotlib
Use Tqdm Progress Bar With Pandas
Splitting Dataframe into Multiple Dataframes
How to Test If a List Contains Another List as a Contiguous Subsequence
How to Enable Autocomplete (Intellisense) for Python Package Modules
In Python, How to Find the Vowels in a Word
Render_Template in Python-Flask Is Not Working
Dividing Each Row by the Previous One
Pyspark - Pass List as Parameter to Udf