0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

substringが言語によって違うので整理してみる

Last updated at Posted at 2023-03-13

概要

JavaScript, C#を使うことが多く毎回substring()で迷っているので整理

substring

  • 文字列から位置を指定して返却する
  • substract stringの略なのだろうか

JavaScript

String.prototype.substring()

  1. indexStart以上の文字列を返す
    • indexStart番目の要素を含む
    • substring(indexStart)
JavaScript
const str = 'abcdefg';
let result = str.substring(2);
console.log(result);
// 'cdefg'
  1. indexStart以上、indexEnd未満の文字列を返す
    • indexStart番目の要素を含む
    • indexEnd番目の要素は含まない
    • substring(indexStart, indexEnd)
JavaScript
const str = 'abcdefg';
let result = str.substring(2, 4);
console.log(result);
// 'cd'

C#

String.Substring メソッド

  1. indexStart以上の文字列を返す
    • Substring(indexStart)
C#
string str = "abcdefg";
var result = str.Substring(2);
Console.WriteLine(result);
// 'cdefg'
  1. indexStartから、indexLengthの長さの文字列を返す
    • Substring(indexStart, indexLength)
C#
string str = "abcdefg";
var result = str.Substring(2, 4);
Console.WriteLine(result);
// 'cdef'

Python

文字列を配列として扱い文字を抽出

Python
alphabet = 'abcdefg'
result = alphabet[indexStart:indexEnd]
  1. indexStart以上の文字列を返す
Python
alphabet:str = 'abcdefg'
result:str = alphabet[2:]
print(result)
// 'cdefg'
  1. indexStart以上、indexEnd未満の文字列を返す
    • indexStart番目の要素を含む
    • indexEnd番目の要素は含まない
Python
alphabet:str = 'abcdefg'
result:str = alphabet[2:4]
print(result)
// 'cd'

まとめ

  • Python,JavaScriptはindexStart以上、indexEnd未満の文字列
  • C#はindexStartからindexLengthの長さの文字列
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?