Python string slicing (substringing) in Java
we have a string "I don't want to learn programming, I want to earn money"
Python slicing:
>>> line[0:10]
"I don't wa"
>>> line[0:-1]
"I don't want to learn programming, I want to earn mone"
>>> line[2:]
"don't want to learn programming, I want to earn money"
>>> line[:]
"I don't want to learn programming, I want to earn money"
>>> line[10:-3]
'nt to learn programming, I want to earn mo'
Python slicing Java implementation:
Python slicing:
>>> line[0:10]
"I don't wa"
>>> line[0:-1]
"I don't want to learn programming, I want to earn mone"
>>> line[2:]
"don't want to learn programming, I want to earn money"
>>> line[:]
"I don't want to learn programming, I want to earn money"
>>> line[10:-3]
'nt to learn programming, I want to earn mo'
Python slicing Java implementation:
public class Solution
{
public static void main(String[] args)
{
String s = "I don't want to learn programming, I want to earn money";
slicer(s, 0, 10);
slicer(s, 0, -1);
slicer(s, 2);
slicer(s);
slicer(s, 10, -3);
}
// using VarArgs to allow using no index, only one ore both
// indexes without method overloading
public static void slicer(String str, int... index)
{
int startIndex;
int endIndex;
if (index.length > 1)
{
startIndex = index[0];
endIndex = index[1];
} else if (index.length == 1)
{
startIndex = index[0];
endIndex = str.length();
} else
{
startIndex = 0;
endIndex = str.length();
}
if (endIndex < 0)
{
endIndex = str.length() + endIndex;
}
char[] sentence = str.toCharArray();
for (int n = startIndex; n < endIndex; n++)
{
System.out.print(sentence[n]);
}
System.out.print("\n");
}
}
No comments:
Post a Comment