Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# 访问字符串


访问字符串

您可以通过在方括号 [] 内引用字符串的索引号来访问字符串中的字符。

此示例打印 myString 中的**第一个字符**

示例

string myString = "Hello";
Console.WriteLine(myString[0]);  // Outputs "H"

动手尝试 »

注意: 字符串索引从 0 开始:[0] 是第一个字符,[1] 是第二个字符,依此类推。

此示例打印 myString 中的**第二个字符**(1)

示例

string myString = "Hello";
Console.WriteLine(myString[1]);  // Outputs "e"

动手尝试 »

您还可以使用 IndexOf() 方法查找字符串中特定字符的索引位置。

示例

string myString = "Hello";
Console.WriteLine(myString.IndexOf("e"));  // Outputs "1"

动手尝试 »

另一个有用的方法是 Substring(),它从指定的字符位置/索引开始提取字符串中的字符,并返回一个新的字符串。此方法通常与 IndexOf() 方法一起使用,以获取特定字符位置。

示例

// Full name
string name = "John Doe";

// Location of the letter D
int charPos = name.IndexOf("D");

// Get last name
string lastName = name.Substring(charPos);

// Print the result
Console.WriteLine(lastName);

动手尝试 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.