Showing posts with label subString. Show all posts
Showing posts with label subString. Show all posts

Monday, 29 March 2021

Php: substr: Return part of a string

Signature

substr ( string $string , int $offset , int|null $length = null ) : string

 

Description

Returns the portion of string specified by the offset and length parameters.

 

If offset is non-negative, the returned string will start at the offset'th position in string, counting from zero.

If offset is negative, the returned string will start at the offset'th character from the end of string.

If string is less than offset characters long, false will be returned.

 

Example

$substr1 = substr($str1, 1, 2);

$substr2 = substr($str1, -3, 3);

 


substr_demo.php

#!/usr/bin/php

<?php

   $str1 = 'Hello';
   $substr1 = substr($str1, 1, 2);
   $substr2 = substr($str1, -3, 3);
   
    echo "\$str1: $str1\n";
    echo "\$substr1: $substr1\n";
    echo "\$substr2: $substr2\n";
?>

 

Output

$./substr_demo.php 

$str1: Hello
$substr1: el
$substr2: llo

 

 

 

Previous                                                    Next                                                    Home

Saturday, 11 April 2020

Java: Remove first character of a string

Using ‘subString’ method, you can extract the string except the first character.

Example
public static String removeFirstChar(String str) {
         if (str == null || str.isEmpty()) {
                  throw new IllegalArgumentException("Input must not be null or empty");
         }
        
         return str.substring(1);

}

StringUtil.java
package com.smaple.app.utils;

public class StringUtil {

 public static String removeFirstChar(String str) {
  if (str == null || str.isEmpty()) {
   throw new IllegalArgumentException("Input must not be null or empty");
  }

  return str.substring(1);

 }
}

StringUtilTest.java

package com.sample.app.utils;

import static com.smaple.app.utils.StringUtil.removeFirstChar;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class StringUtilTest {

 @Test(expected = IllegalArgumentException.class)
 public void inputIsNull() {
  String text = null;

  removeFirstChar(text);
 }

 @Test(expected = IllegalArgumentException.class)
 public void inputIsEmpty() {
  String text = "";

  removeFirstChar(text);
 }

 @Test
 public void inputLengthIs1() {
  String text = "a";
  String expected = "";
  
  String result = removeFirstChar(text);
  assertEquals(expected, result);
 }

 @Test
 public void inputLengthIsGreaterThan1() {
  String text = "hello";
  String expected = "ello";

  String result = removeFirstChar(text);

  assertEquals(expected, result);

 }
}


You may like