I want the find the first vowel in a string (apellidoPat) for example if my string it's "CRUZ" my expexted output is : "U" to concatenate in rfc what can I use ? a loop ??
rfc : first letter of apellidoPat + first vowel of apellidoPat + irst letter of apellidoMat + date (YYMMDD)
I have all except first vowel of apellidoPat
private String getRFC() {
String rfc = "";
String apellidoPat = "CRUZ";
String apellidoMat = "HERNANDEZ";
String nombre = "JAVIER";
String fechaNac = "1997-12-25";
rfc = apellidoPat.substring(0,1) + "FIST VOWEL apellidoPat" + apellidoMat.substring(0,1) + nombre.substring(0,1) + fechaNac.substring(2,4) + fechaNac.substring(5,7) + fechaNac.substring(8,10);
// Expected output: CUHJ971225
return rfc
}
You do not need to add the date part by part to avoid -, it is better to split it by - and join the parts together to get desired result. And you can use a loop to find first vowel:
private String getRFC(){
String vowels = "AEIOUaeiou";
String apellidoPat = "CRUZ";
String apellidoMat = "HERNANDEZ";
String fechaNac = "1997-12-25";
// first letter of apellidoPat
String rfc = String.valueOf(apellidoPat.charAt(0));
// first vowel of apellidoPat
for (int i = 0; i < apellidoPat.length(); ++i){
if (vowels.indexOf(apellidoPat.charAt(i)) != -1){
rfc += String.valueOf(apellidoPat.charAt(i));
break;
}
}
// first letter of apellidoMat + date (YYMMDD)
rfc += apellidoMat.charAt(0) + String.join("", fechaNac.split("-"));
return rfc;
}
To get the first vowel of a string, you can try:
static final String vowels = "aeiou";
int indexOfFirstVowel = indexOfFirstVowel(apellidoPat);
private static int indexOfFirstVowel(String word){
String loweredWord = word.toLowerCase();
for (int index=0; index<loweredWord.length(); index++)
{
if (vowels.contains(String.valueOf(loweredWord.charAt(index))))
{
return index;
}
}
return -1;
}
Explanation:
indexOfFirstVowel method return the index of the first vowel in case it is found. Otherwise, it will return -1. You can change as per your requirement.
In case of String apellidoPat = "CRUZ"; this method return 2 i.e. index of U.
You can try below code.
String rfc;
String apellidoPat = "CRUZ";
int indexOfFirstVowel = indexOfFirstVowel(apellidoPat);
String apellidoMat = "HERNANDEZ";
String nombre = "JAVIER";
String fechaNac = "1997-12-25";
rfc = apellidoPat.substring(0, 1);
if(indexOfFirstVowel != -1) {
rfc += apellidoPat.charAt(indexOfFirstVowel);
}
rfc += apellidoMat.substring(0,1) + nombre.substring(0,1) + fechaNac.substring(2,4) + fechaNac.substring(5,7) + fechaNac.substring(8,10);
System.out.println(rfc);
Find first vowel from string and add it to a var
You can do it by replacing all characters except the vowels with an empty string and get the first character from the replaced string.
public class Main {
public static void main(String[] args) {
String apellidoPat = "CRUZ";
String replacedStr = apellidoPat.replaceAll("[^AEIOUaeiou]", "");
String firstVowel = "";
if (!replacedStr.isEmpty()) {
firstVowel = replacedStr.substring(0, 1);
}
System.out.println(firstVowel);
}
}
Output:
U
Thus, in your case, it will be:
rfc = firstVowel + "FIST VOWEL apellidoPat" + apellidoMat.substring(0,1) + nombre.substring(0,1) + fechaNac.substring(2,4) + fechaNac.substring(5,7) + fechaNac.substring(8,10);
Note: Check this for the explanation of the regex I have used with String#replaceAll.
you can use a for loop for this intention. for example :
String text = "CRUZ";
String vawel = "aeiouAEIOU";
for(int i=0 ; i<text.length() ; i++)
{
char ch = text.charAt(i);
if(vawel.contains(String.valueOf(ch)))
{
//add to your variable
}
}
Related
public class Main {
public static void main(String[] args) {
String name = "the-stealth-warrior";
for (int i = 0; i < name.length();i++){
if (name.charAt(i) == '-'){
char newName = Character.toUpperCase(name.charAt(i+1));
newName += name.charAt(i + 1);
i++;
}
}
}
}
I try to loop in every char and check if the I == '-' convert the next letter to be uppercase and append to a new String.
We can try using a split approach with the help of a stream:
String name = "the-stealth-warrior";
String parts = name.replaceAll("^.*?-", "");
String output = Arrays.stream(parts.split("-"))
.map(x -> x.substring(0, 1).toUpperCase() + x.substring(1))
.collect(Collectors.joining(""));
output = name.split("-", 2)[0] + output;
System.out.println(output); // theStealthWarrior
I think the most concise way to do this would be with regexes:
String newName = Pattern.compile("-+(.)?").matcher(name).replaceAll(mr -> mr.group(1).toUpperCase());
Note that Pattern.compile(...) can be stored rather than re-evaluating it each time.
A more verbose (but probably more efficient way) to do it would be to build the string using a StringBuilder:
StringBuilder sb = new StringBuilder(name.length());
boolean uc = false; // Flag to know whether to uppercase the char.
int len = name.codePointsCount(0, name.length());
for (int i = 0; i < name.len; ++i) {
int c = name.codePointAt(i);
if (c == '-') {
// Don't append the codepoint, but flag to uppercase the next codepoint
// that isn't a '-'.
uc = true;
} else {
if (uc) {
c = Character.toUpperCase(c);
uc = false;
}
sb.appendCodePoint(c);
}
}
String newName = sb.toString();
Note that you can't reliably uppercase single codepoints in specific locales, e.g. ß in Locale.GERMAN.
I need to write encryptor.
The first letter needs to be converted to its ASCII code.
The second letter needs to be switched with the last letter
It should make from this "65 119esi 111dl 111lw 108dvei 105n 97n 111ka"
This "A wise old owl lived in an oak"
But when I check is char a digit i have an error.
public static void encryptThis(String text) {
String [] text_arr = text.split("\\s");
for(int i = 0; i < text_arr.length;i++){
String word = text_arr[i];
int length = word.length();
char [] char_word = new char [length];
char_word = word.toCharArray();
int k = 0;
length = char_word.length;
char [] numb = new char [length];
for (int j = 0;j < length; j++){
//In this place
if (Character.isDigit(char_word[i])){
numb[k] = char_word[i];
char_word[i] = ' ';
k++;
System.out.println(numb[k]);
}
}
int number = Integer.parseInt(numb.toString(),8);
String edit_char_word = char_word.toString();
String final_str = new StringBuffer(edit_char_word).reverse().toString().trim();
final_str = number + final_str;
text_arr[i] = final_str;
}
String fin_text = text_arr.toString();
return fin_text;
}
I wrote the encryptThis method from the beginning and tried to stay as simple to get readable code, here is
a full working example. As you did not mention what to do if a number is the first "letter" there is no
special handling for this - an "1" will be encrypted to (ascii) 49...
public class Main_So {
public static void main(String[] args) {
System.out.println("https://stackoverflow.com/questions/62460366/in-function-isdigit-java-lang-arrayindexoutofboundsexception-5");
String input = "A wise old owl lived in an oak";
String outputExpected = "65 119esi 111dl 111lw 108dvei 105n 97n 111ka";
System.out.println("input: " + input);
String output = encryptThis(input);
System.out.println("output encryptThis: " + output);
System.out.println("output expected: " + outputExpected);
}
public static String encryptThis(String text) {
String[] text_arr = text.split("\\s");
String outputString = "";
for (int i = 0; i < text_arr.length; i++) {
String word = text_arr[i];
int length = word.length();
int ascii0 = (int) word.charAt(0);
String word0 = String.valueOf(ascii0); // first char as ascii code
String subString = word.substring(1);
if (length > 2) { // switch chars if string length > 2
char char1 = word.charAt(1);
char charEnd = word.charAt(length - 1);
StringBuilder wordBuilder = new StringBuilder(subString);
wordBuilder.setCharAt(0, charEnd);
wordBuilder.setCharAt((length - 2), char1);
subString = String.valueOf(wordBuilder);
}
outputString = outputString + word0 + subString + " ";
}
return outputString;
}
}
This is the result:
input: A wise old owl lived in an oak
output encryptThis: 65 119esi 111dl 111lw 108dvei 105n 97n 111ka
output expected: 65 119esi 111dl 111lw 108dvei 105n 97n 111ka
I have written following code to get next word from a string in Java. I feel its very raw and I shouldn't have to write so much code for this but couldn't find any other way. Want to know if there are better ways available to do same:
public static String getNextWord(String str, String word) {
String nextWord = null;
// to remove multi spaces with single space
str = str.trim().replaceAll(" +", " ");
int totalLength = str.length();
int wordStartIndex = str.indexOf(word);
if (wordStartIndex != -1) {
int startPos = wordStartIndex + word.length() + 1;
if (startPos < totalLength) {
int nextSpaceIndex = str.substring(startPos).indexOf(" ");
int endPos = 0;
if (nextSpaceIndex == -1) {
// we've reached end of string, no more space left
endPos = totalLength;
} else {
endPos = startPos + nextSpaceIndex;
}
nextWord = str.substring(startPos, endPos);
}
}
return nextWord;
}
Note: the input word could be anything (multi words, single word, a word not in string etc).
Test:
String text = "I am very happy with life";
System.out.println(StringUtil.getNextWord(text, "I"));
System.out.println(StringUtil.getNextWord(text, "I am"));
System.out.println(StringUtil.getNextWord(text, "life"));
System.out.println(StringUtil.getNextWord(text, "with"));
System.out.println(StringUtil.getNextWord(text, "fdasfasf"));
System.out.println(StringUtil.getNextWord(text, text));
Output:
am
very
null
life
null
null
This sounds like a job for regex. Something like this:
public static String getNextWord(String str, String word){
Pattern p = Pattern.compile(word+"\\W+(\\w+)");
Matcher m = p.matcher(str);
return m.find()? m.group(1):null;
}
Hope this will serve your purpose.
public static String getNextWord(String str, String word) {
String[] words = str.split(" "), data = word.split(" ");
int index = Arrays.asList(words).indexOf((data.length > 1) ? data[data.length - 1] : data[0]);
return (index == -1) ? "Not Found" : ((index + 1) == words.length) ? "End" : words[index + 1];
}
Input (single word) :
String str = "Auto generated method stub";
String word = "method";
Out Put:
next word: stub
Input (multi-words) :
String str = "Auto generated method stub";
String word = "Auto generated";
Out Put:
next word: method
Input (missing word) :
String str = "Auto generated method stub";
String word = "was";
Out Put:
next word: Not Found
Input (end word) :
String str = "Auto generated method stub";
String word = "stub";
Out Put:
next word: End
You can create an array of words by doing this:
String[] words = str.split(" ");
This splits the string into strings when separated by a space. Note you keep needing to trim the str as you want to.
Now, you can somehow search in the array by finding some word and adding 1 to the index to get the next one.
nextword = words[words.indexOf(word) + 1];
I think, this solution works correctly:
public static String getNextWord(String str, String word) {
String[] strArr = str.split(word);
if(strArr.length > 1) {
strArr = strArr[1].trim().split(" ");
return strArr[0];
}
return null;
}
You can try the below code.
public static String getNextWord(String str, String word) {
try {
List<String> text = Arrays.asList(str.split(" "));
List<String> list = Arrays.asList(word.split(" "));
int index_of = text.indexOf(list.get(list.size() - 1));
return (index_of == -1) ? null : text.get(index_of + 1);
} catch(Exception e) {
return null;
}
}
Hope this is what you are looking for:
public static void main(String[] args) {
String text = "I am very happy with life";
System.out.println(getNextWord(text,"am"));
System.out.println(getNextWord(text,"with"));
System.out.println(getNextWord(text,"happy"));
System.out.println(getNextWord(text,"I"));
System.out.println(getNextWord(text,"life"));
}
public static String getNextWord(String text,String finditsNext){
String result = "There is no next string";
try {
int findIndex = text.indexOf(finditsNext);
String tep = text.substring(findIndex);
if(tep.indexOf(" ") >0) {
tep = tep.substring(tep.indexOf(" ") + 1);
if(tep.indexOf(" ") >0)
result = tep.substring(0, tep.indexOf(" "));
else
result = tep;
}
}catch (IndexOutOfBoundsException ex){
}
return result;
}
The output for the above is:
very
life
with
am
There is no next string
How to Split a String based on the nth(Ex: second) occurence of a delimiter.whereas other than the nth occurence ,all other delimiters should be retained
I/P:
String name="This is my First Line";
int delimiter=" ";
int count=3;//This is a dynamic value
O/P:
String firstpart=This is my
String Secondpart=First Line
Due to limitations with regex, you can't split it in 1 line of code, but you can do it in 2 lines:
String firstPart = name.replaceAll("^((.*?" + delimiter + "){" + count + "}).*", "$1");
String secondPart = name.replaceAll("^(.*?" + delimiter + "){" + count + "}(.*)", "$2");
I got it like this
String name="This is my First Line";
int count=3;
String s1,s2;
String arr[]=name.split();//default will be space
for(i=0;i<arr.length;i++)
if(i<count)
s1=s1+arr[i]+" "
else
s2=s2+arr[i]+" "
Just use indexOf to search for the delimiter and repeat that until you found it count-times. Here is a snippet:
String name = "This is my First Line";
String delimiter = " ";
int count = 3;
// Repeativly search for the delimiter
int lastIndex = -1;
for (int i = 0; i < count; i++) {
// Begin to search from the position after the last matching index
lastIndex = name.indexOf(delimiter, lastIndex + 1);
// Could not be found
if (lastIndex == -1) {
break;
}
}
// Get the result
if (lastIndex == -1) {
System.out.println("Not found!");
} else {
// Use the index to split
String before = name.substring(0, lastIndex);
String after = name.substring(lastIndex);
// Print the results
System.out.println(before);
System.out.println(after);
}
It will now output
This is my
First Line
Note the whitespace (the delimiter) at the beginning of the last line, you can omit this if you want by using the following code at the end
// Remove the delimiter from the beginning of 'after'
String after = ...
after = after.subString(delimiter.length());
static class FindNthOccurrence
{
String delimiter;
public FindNthOccurrence(String del)
{
this.delimiter = del;
}
public int findAfter(String findIn, int findOccurence)
{
int findIndex = 0;
for (int i = 0; i < findOccurence; i++)
{
findIndex = findIn.indexOf(delimiter, findIndex);
if (findIndex == -1)
{
return -1;
}
}
return findIndex;
}
}
FindNthOccurrence nth = new FindNthOccurrence(" ");
String string = "This is my First Line";
int index = nth.nthOccurrence(string, 2);
String firstPart = string.substring(0, index);
String secondPart = string.substring(index+1);
Simply like this,
Tested and work perfectly in Java 8
public String[] split(String input,int at){
String[] out = new String[2];
String p = String.format("((?:[^/]*/){%s}[^/]*)/(.*)",at);
Pattern pat = Pattern.compile(p);
Matcher matcher = pat.matcher(input);
if (matcher.matches()) {
out[0] = matcher.group(1);// left
out[1] = matcher.group(2);// right
}
return out;
}
//Ex: D:/folder1/folder2/folder3/file1.txt
//if at = 2, group(1) = D:/folder1/folder2 and group(2) = folder3/file1.txt
I'm trying to return strings in different lines given these conditions. Since I cannot use the += in Java with strings, how do I make one giant string that is spaced per line but "stacks?" In other words, how do I add a new string within a loop to an old string?
/**
Returns a String that concatenates all "offending"
words from text that contain letter; the words are
separated by '\n' characters; the returned string
does not contain duplicate words: each word occurs
only once; there are no punctuation or whitespace
characters in the returned string.
#param letter character to find in text
#return String containing all words with letter
*/
public String allWordsWith(char letter)
{
String result = "";
int i = 0;
while (i < text.length())
{
char newchar = text.charAt(i);
if (newchar == letter)
{
int index1 = text.lastIndexOf("",i);
int index2 = text.indexOf("",i);
String newstring = '\n' + text.substring(index2,index1);
}
i++;
}
return result;
}
Modify the result string, and fix your "word boundary" tests.
if (newchar == letter) {
int index1 = text.lastIndexOf(' ',i);
int index2 = text.indexOf(' ',i);
// TODO -- handle when index1 or index2 is < 0; that means it wasn't found,
// and you should use the string boundary (0 or length()) instead.
String word = text.substring( index2,index1);
result += "\n" + word;
}
If you were really concerned about performance you could use a StringBuilder and append(), but otherwise I strongly favour += for being concise & readable.
you are re-initializing your string in loop every time. Move the string declaration outsid eof loop:
Replace this
String newstring = '\n' + text.substring(index2,index1);
with
result = '\n' + text.substring(index2,index1);
First, use a StringBuilder.
Second, use System.getProperty("line.separator") to ensure proper line breaks are used.
Edited code:
public String allWordsWith(char letter)
{
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < text.length())
{
char newchar = text.charAt(i);
if (newchar == letter)
{
int index1 = text.lastIndexOf("",i);
int index2 = text.indexOf("",i);
sb.Append(text.substring(index2,index1));
sb.Append(System.getProperty("line.separator"));
//I put the new line after the word so you don't get an empty
//line on top, but you can do what you need/want to do in this case.
}
i++;
}
return result;
}
Use StringBuilder as following:
public String allWordsWith(char letter){
//String result = "";
StringBuilder result = new StringBuilder();
int i = 0;
while (i < text.length()){
char newchar = text.charAt(i);
if (newchar == letter){
int index1 = text.lastIndexOf("",i);
int index2 = text.indexOf("",i);
result.append('\n' + text.substring(index2,index1));
}
i++;
}
return result.toString();
}
String text = "I have android code with many different java, bmp and xml files everywhere in my project that I used during the drafting phase of my project.";
String letter = "a";
Set<String> duplicateWordsFilter = new HashSet<String>(Arrays.asList(text.split(" ")));
StringBuilder sb = new StringBuilder(text.length());
for (String word : duplicateWordsFilter) {
if (word.contains(letter)) {
sb.append(word);
sb.append("\n");
}
}
return sb.toString();
result is:
android
have
java,
drafting
and
many
that
phase