[程式開發技巧] 隱藏部分字串(適用帳號, 身分證顯示) | 多語言版本c#, java, python, js, ts, php

本篇教你如何隱藏字串中的部分字元

(C#)

public string HidePartText(string origin, char replaceChar)
{
    int halfLength = origin.Length / 2;
    string partText = origin.Substring(0, origin.Length - halfLength);
    return partText.PadRight(origin.Length, replaceChar);
}

(Java)

public String hidePartText(String origin, char replaceChar)
{
    int halfLength = origin.length() / 2;
    String partText = origin.substring(0, origin.length() - halfLength);
    String rightPadding = String.format("%-" + halfLength + "s", "").replace(' ', replaceChar);
    return partText + rightPadding;
}

(Python)

def hidePartText(origin, replaceChar):
    halfLength = (int)(len(origin) / 2)
    partText = origin[0:len(origin) - halfLength]
    return partText.ljust(len(origin), replaceChar)

(JavaScript)

function hidePartText(origin, replaceChar) {
  const halfLength = Math.floor(origin.length / 2);
  let partText = origin.substring(0, origin.length - halfLength);
  return partText.padEnd(origin.length, replaceChar);
}

(TypeScript)

function hidePartText(origin: string, replaceChar: string): string {
  const halfLength: number = Math.floor(origin.length / 2);
  let partText = origin.substring(0, origin.length - halfLength);
  return partText.padEnd(origin.length, replaceChar);
}

(PHP)

function hidePartText($origin, $replaceChar) {
    $halfLength = (int)(strlen($origin) / 2);
    $partText = substr($origin, 0, strlen($origin) - $halfLength);
    return str_pad($partText, strlen($origin), $replaceChar, STR_PAD_RIGHT);
}


範例中會自動將後半部的字串
取代成你所輸入的字元

留言