String etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
String etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

15 Ekim 2023 Pazar

String.splitWithDelimiters metodu - Java 21

Giriş
Java 21 ile geliyor. İmzası şöyle
String[] splitWithDelimiters(String regex,
int limit)
Örnek
Şöyle yaparız
var str = "foo:::bar::hello:world";
var regex = ":+"; // at least one colon

var result = str.splitWithDelimiters(regex, -1);
// => String[7] { "foo", ":::", "bar", "::", "hello", ":", "world" }


String.indexOf metodu

Giriş
En baştan veya belirtilen indeksten başlayarak Character veya String aramak içindir

indexOf - character
İmzası şöyle
public int indexOf(int ch)
indexOf - character + fromIndex
İmzası şöyle
public int indexOf(int ch, int fromIndex)
indexOf - String
İmzası şöyle
public int indexOf(String str)
Örnek
Şöyle yaparız. contains() metodu indexOf () metoduna çok benzer. İkisi de belirtilen string'in kendi içimde olup olmadığını döner. Tek fark olarak contains() boolean dönerken indexOf () başlangıç konumunu belirtir.
String largeValue  = "2323254534534642342354346876985374";
String searchValue = "32545345346423423543468769";
if(largeValue.contains(searchValue)){
  System.out.println("The index is : "+largeValue.indexOf(searchValue));
}
indexOf - String + fromIndex
İmzası şöyle
public int indexOf(String str, int fromIndex)
Java 21
Açıklaması şöyle
We already had 4 different indexOf methods available to find the index of an int or String argument, starting at the beginning or a given index.

Java 21 added another variant for both finding either an int or String by providing an end-index in addition to a beginning one
İmzası şöyle
int indexOf(int ch,
            int beginIndex,
            int endIndex)

int indexOf(String str,
            int beginIndex,
            int endIndex)
Açıklaması şöyle
Be aware that the beginIndex is inclusive, but the endIndex is exclusive. In my opinion, they should’ve named them accordingly, as they did with IntStream.rangeClosed for example.






24 Şubat 2023 Cuma

String.describeConstable metodu

Giriş
Açıklaması şöyle
The method Optional<String> describeConstable()returns an Optional containing the nominal descriptor for the given string, which is the string itself.
Örnek
Şöyle yaparız
String s = "Java";
Optional<String> optionalS = s.describeConstable();
System.out.println(optionalS.get());

String.resolveConstantDesc metodu

Giriş
Açıklaması şöyle
The method String resolveConstantDesc(Lookup lookup)resolves the given string as ConstantDesc and returns the string itself.
Örnek
Şöyle yaparız
System.out.println("Java".resolveConstantDesc(MethodHandles.lookup()));

23 Şubat 2023 Perşembe

String.translateEscapes metodu

Giriş
Açıklaması şöyle
The method String translateEscapes() returns a new String with escape sequences translated if present in the original string.
Örnek
Şöyle yaparız
String s = "java\\nhello\\tword";
System.out.println(s); // Output: java\nhello\tword

System.out.println(s.translateEscapes()); 
// Output: 
// java
// hello word

String.join metodu

Giriş
İlk parametre ayraçtır. Stringleri birleştirir. Son son string'den sonra ayracı eklemez. Açıklaması şöyle. Yani CSV tarzı şeyleri oluşturmak için ideal :)
The join method offers the convenience of not adding the delimiter at the end of the string as well.
İmzası şöyle
public static String join(CharSequence delimiter, CharSequence... elements)
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
CharSequence
Örnek
Şöyle yaparız
String joined = String.join("-", "java", "programming", "hello", "world");
System.out.println(joined); // Output: java-programming-hello-world

String joined2 = String.join("", "java", "programming", "hello", "world");
System.out.println(joined2); // Output: javaprogramminghelloworld
Örnek
Şöyle yaparız.
String.join(delimeter, foo, bar, baz, foo1, bar1);
Iterable
Örnek
Şöyle yaparız
List<String> list = List.of("java", "programming", "hello", "world");
String joined = String.join(", ", list);
System.out.println(joined); // Output: java, programming, hello, world











String.transform metodu

Giriş
Java 12 ile geliyor. İmzası şöyle
public <R> R transform(Function<? super String, ? extends R> f)
Örnek
Şöyle yaparız
Function<String, String> titleCase = s -> 
  Character.toUpperCase(s.charAt(0)) + s.toLowerCase().substring(1);
System.out.println("animal".transform(titleCase)); // Animal

Function<String, Integer> converToInt = Integer::parseInt;
int num = "123".transform(converToInt);
System.out.println(num); // 123

String.indent metodu

Giriş
Java 12 ile geliyor. Her satırın başına belirtilen sayı kadar boşluk ekler

Örnek
Şöyle yaparız
String poem = "Two loves I have of comfort and despair,\n" +
                "Which like two spirits do suggest me still:\n" +
                "The better angel is a man right fair,\n" +
                "The worser spirit a woman color’d ill.\n";

System.out.println(poem);
System.out.println(poem.indent(4));
System.out.println(poem.indent(10));


Two loves I have of comfort and despair,
Which like two spirits do suggest me still:
The better angel is a man right fair,
The worser spirit a woman colord ill.

    Two loves I have of comfort and despair,
    Which like two spirits do suggest me still:
    The better angel is a man right fair,
    The worser spirit a woman colord ill.
          
          Two loves I have of comfort and despair,
          Which like two spirits do suggest me still:
          The better angel is a man right fair,
          The worser spirit a woman colord ill.


String.repeat metodu - String'in Kendisini Tekrarlar

Giriş
Java 11 ile geliyor. Açıklaması şöyle
Repeats the String as many times as provided by the int parameter
İmzası şöyle
public String repeat(int count)
Eskiden Apache StringUtils kullanılırdı. Yani şöyle yapardık. Şimdi artık gerek yok
String str = "...";

String repeatedStr = StringUtils.repeat(str, 3);
String repeatedStr2 = str.repeat(3);

Örnek
Şöyle yaparız.
System.out.println("java".repeat(5));    // javajavajavajavajava
System.out.println("apple, ".repeat(4)); //apple, apple, apple, apple, 
System.out.println("*".repeat(10));      // *********
Örnek
Şöyle yaparız.
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");

String.lines metodu - Java 11 İle Geliyor, Stream Döndürür

Giriş
Java 11 ile geliyor. Açıklaması şöyle.
Uses a Spliterator to lazily provide lines from the source string
İmzası şöyle
public Stream<String> lines()
Örnek
Şöyle yaparız.
String output = paragraph.lines().collect(Collectors.joining());
Örnek
Şöyle yaparız
String sentence = "marry\n had\n a\n little\n lamb";
Stream<String> lineStream = sentence.lines();
lineStream.forEach(System.out::println);
// marry
// had
// a
// little
// lamb


System.out.println("The sentence has a total of " + sentence.lines().count() + " lines");

// The sentence has a total of 5 lines

17 Ağustos 2021 Salı

String.format metodu

Giriş
İmzası şöyle
public static String format(String format, Object... args) 
public static String format(Locale l, String format, Object... args) {
Söz dizimi şöyle. Her zaman % format specifier ile başlar
%<index$><flags><width><.precision><conversion>
Locale Kullanımı
Örnek
Şöyle yaparız
String name = "Tandrew";
int age = 16;

String formattedString = String.format(Locale.US, "My name is %s and I am %d years old",
  name, age);

// notice the format specifiers %s and %d
System.out.println(formattedString); 

// Output: My name is Tandrew and I am 16 years old
1. Index
Açıklaması şöyle
<index$> is an optional positive integer that corresponds to an argument in the argument list. This index starts at 1 (i.e., the first argument in the argument list is indexed as 1). Therefore, the first argument in the argument list can be addressed using 1$, the second argument can be addressed using 2$, and so on. For example, we can format a String — which has a conversion of s— that corresponds to the second argument in our argument list using the following format specifier:
Örnek
Şöyle yaparız
String.format("The hex value of %d is 0x%1$h",8756);//"The hex value of 8756 is 0x2234"
2. Flags
Flags şöyle
-            Left-justifies the results.
#           Uses an alternative form.
+           Always includes a sign.
(space) Add leading space for positive values.
0           Zero-pads the result.
,            Includes locale-specific grouping separators.
(            Encloses negative numbers in parenthesis.

3. Width
Örnek
Şöyle yaparız
Birinci örnekte % formatlamaya başlama karakteridir, 10 width içindir gerekirse sağa doğru doldurulur, s ise parametrenin string olarak formatlanacağını belirtir
İkinci örnekte % formatlamaya başlama karakteridir, -10 width içindir ve gerekirse sola doğru doldurulur, s ise parametrenin string olarak formatlanacağını belirtir
String formattedString1 = String.format("%10s", "name");    // Result: "name      "
String formattedString2 = String.format("%-10s", "name");   // Result: "      name"
Örnek
Şöyle yaparız.
0 baş tarafı doldurma karakteridir, 32 width içindir,  x ise parametrenin hexadecimal olarak formatlanacağını belirtir
BigInteger n = ...;
String md5h = String.format("%032x",n);
4. Precision
Açıklaması şöyle
General: 
Maximum number of characters displayed; if the supplied argument results in more characters than the supplied precision, the resulting string is truncated to the correct number of characters. For example, supplying Justin as an argument to the format specifier %.1s result in J.

Floating point (e, E, and f): 
Number of digits after the decimal place. For example, a format specifier of %.1f with an argument of 1.2345 results in 1.2.

Floating point (g, G, a and A): 
Number of digits in the magnitude after rounding.
5. Conversion Tablosu
Conversion Tablosu şöyle
%b, B : true, false, TRUE, FALSE
%h, H : fff03,6199ec4,6199EC4
%s, S : foo ,bar, BAR
%c, C : c, f ,F
%d :     10,5347
%o :      2,151
%x, X :  ff4,e56d2,E56D2
%e, E :  1.114313e+09,1.682340e-08,1.682340E-08
%f :       4.562340, 1245.643876
%g, G : 128636, 8.12935e+16,3546.50,8.12935E+16
%a, A :  0x1.63c774a3d70a4p19, 0x1.187ff0337c5abp-26, 0X1.8D7025536252DP45

Boolean %b veya %B
Açıklaması şöyle
The boolean result as a string (e.g., true or false) if the supplied argument is a Boolean. false if the supplied argument is null and true for all other arguments. If B is used, the resulting boolean value is capitalized (e.g., TRUE or FALSE).
Hexadecimal String -%h veya %h
Açıklaması şöyle. fff03, 6199ec4, 6199EC4 gibi
The hexadecimal value of the supplied argument, arg, by applying the expression Integer.toHexString(arg.hashCode()). Note that the result does not include a 0x prefix. If H is used, the resulting alphabetic hexadecimal characters are capitalized.
String - %s
Açıklaması şöyle
The provided argument as a string (by invoking Object.toString). If the supplied argument is a Formattable object, the string is obtained by invoking Formattable.formatTo. If S is supplied, the supplied string is capitalized.
Şöyle yaparız.
int a = ...;
int b = ...;
int c = ...;
return String.format("%s-%s-%s", a, b, c);
Character %c veya %C
Açıklaması şöyle
The Unicode character. If a String object is supplied, an IllegalFormatConversionException is thrown. If C is used, the supplied character is capitalized.
Integer -%d
Açıklaması şöyle
The decimal integer.
Şöyle yaparız.
String.format("%011d", 4366)
Çıktı olarak şunu alırız
00000004366
Octal Integer -%o
Açıklaması şöyle. 12, 151 gibi
The octal integer.
hexadecimal Integer - %x veya %X
Açıklaması şöyle. ff4, e56d2, E56D2 gibi
The hexadecimal integer. Note that the result does not include a 0x prefix. This specifier should be preferred over h when supplying an integer. If X is used, the resulting alphabetic hexadecimal characters are capitalized.
Şöyle yaparız.
int a = ...;
System.out.println( String.format("%X", a) );
Floating Point - %e veya %E
Açıklaması şöyle. 1.114313e+09, 1.682340e-08, 1.682340E-08 gibi
The value in scientific notation. If E is used, the exponent symbol (e) is capitalized (i.e., E).
Floating Point - %f
Açıklaması şöyle.
Use %.4f to perform the rounding you want. This format specifier indicates a floating point value with 4 digits after the decimal place. Half-up rounding is used for this, meaning that if the last digit to be considered is greater than or equal to five, it will round up and any other cases will result in rounding down.
Örnek
Şöyle yaparız.
String.format("%.2f", 62.1232131342);
Floating Point In Scientific Notation Or Decimal Format- %g
Açıklaması şöyle. 128636, 8.12935e+16, 3546.50, 8.12935E+16 gibi
The value in scientific notation or decimal format, depending on the result after rounding. If G is used, the exponent symbol (e) is capitalized (i.e., E).
Açıklaması şöyle.
The %g format specifier is used to indicate how many significant digits in scientific notation are displayed. Leading zeroes are not significant, so they are skipped.
Örnek
Şöyle yaparız. Çıktı olarak 0.1235 alırız
String.format("%.4g", 0.1234712)
Örnek
Şöyle yaparızz. Çıktı olarak 0,0009877 alırız
String.format("%.4g", 0.000987654321)
Floating Point In Scientific Notation - %a veya %A
Açıklaması şöyle.  0x1.63c774a3d70a4p19, 0x1.187ff0337c5abp-26, 0X1.8D7025536252DP45 gibi
The value in scientific notation, where the significand is a hexadecimal floating point value, and the power follows a p delimiter. If A is used, the resulting alphabetic hexadecimal characters are capitalized and the p delimiter is capitalized (i.e., P).