是否有内置函数在.net中重复字符串或字符?

时间:2010-11-06 20:41:04

标签: c# asp.net vb.net

c#中是否有一个函数返回给定char或string的x次。或者我必须编码吗?

5 个答案:

答案 0 :(得分:52)

string.Concat(Enumerable.Repeat("ab", 2));

返回

  

“ABAB”

答案 1 :(得分:51)

string.Join("", Enumerable.Repeat("ab", 2));

返回

"abab"

string.Join("", Enumerable.Repeat('a', 2))

返回

"aa"

答案 2 :(得分:27)

对于字符串,你应该使用Kirk的解决方案:

string.Join("", Enumerable.Repeat("ab", 2));

但是对于字符,您可以使用内置(更高效)的字符串构造函数:

new string('a', 2); // returns aa

答案 3 :(得分:3)

new String('*', 5)

请参阅Rosetta Code

答案 4 :(得分:0)

最好的解决方案是内置的字符串函数:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="navholder justify-content-center">
<nav class="navbar navbar-expand-lg navbar-light bg-light justify-content-center">
  <!-- Toggler/collapsible Button using Fontawesome icon -->
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>   
  <div class="collapse navbar-collapse colour1bg" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item central">
        <a class="nav-link" href="#">Link1</a>
      </li>
      <li class="nav-item central">
        <a class="nav-link" href="#">Link2</a>
      </li>
      <li class="nav-item central">
        <a class="nav-link" href="#">Link3</a>
      </li>
      <li class="nav-item central">
        <a class="nav-link" href="#">Link4</a>
      </li>    
      <li class="nav-item central">
        <a class="nav-link" href="#">Link5</a>
      </li>    
      <li class="nav-item central">
        <a class="nav-link" href="#">Link6</a>
      </li> 
    </ul>
  </div>

</nav>
</div>

<p>some text...</p>