Answer the question
In order to leave comments, you need to log in
How can I improve my code to work with punctuation marks?
The essence of the task: Replace in the text all words no longer than 6 characters in reverse order, starting
with a consonant letter.
I wrote a code that works with spaces, but I have no idea how to work with other punctuation marks, I will be grateful for any help
public class Main
{
public static void main (String[] args)
{
char[] cons = {'б','в','г', 'д','ж','й','з','к','л','м','н','п','р','с','т','ф','ч','х','ц','ш','щ'};
int sovp = 0;
String task = "Заменить в тексте все слова длиной не больше 6 символов в обратном порядке начинающиеся на согласную букву ";
task = task.toLowerCase();
System.out.println(task);
String[] strArr = task.split(" ");
for (int i=0;i<strArr.length;i++)
{
char first = strArr[i].charAt(0);
for (int a= 0; a < 21; a++)
{
if (first == cons[a])
{
sovp = 1;
}
}
if ((strArr[i].length() <= 6) && (sovp==1))
{
StringBuffer sBuffer = new StringBuffer(strArr[i]);
sBuffer.reverse();
System.out.print(sBuffer + " ");
sovp = 0;
}
else
System.out.print(strArr[i] +" ");
}
}
}
Answer the question
In order to leave comments, you need to log in
You can use lookahead and lookbehind, which are regular expression functions.
You can even place placeholders for example and use to replace the placeholders with the actual string you need to use.
Simple solution for Java 8 and newer:%1$s
String.format
public class Main {
public static final String DELIMITER = "((?<=%1$s)|(?=%1$s))";
public static void main(String[] args) {
String task = "Заменить, в тексте все! слова длиной? не больше 6 символов; в обратном порядке начинающиеся на: согласную букву ";
String[] arr = task.split(String.format(DELIMITER, "[:?;!. ]"));
String result = Arrays.stream(arr)
.map(s -> !check(s.charAt(0)) && !length(s) ? reverse(s) : s)
.collect(Collectors.joining());
System.out.println(result); /* Заменить, в етскет есв! аволс йонилд? ен ешьлоб 6 символов; в обратном порядке начинающиеся ан: согласную увкуб */
}
public static boolean check(char c) {
return "аиеёоуыэюя".indexOf(c) > -1;
}
public static boolean length(String s) {
return s.length() > 6;
}
public static String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question